Archived

This topic is now archived and is closed to further replies.

d000hg

Singletons?

Recommended Posts

If I make a class a singleton, does that mean I can have a public static variable which is a pointer to the instance, thus allowing me to access non-static methods without knowing about an instance of that class? Assumming this works, would you ever want to do it - why not make everything in the class static? Now it''s guaranteed as a singleton without any messing about. John 3:16

Share this post


Link to post
Share on other sites
Making everything static in a class is the Monostate pattern,
not the Singleton.

With Monostate, you get a similar effect that you can''t
"instantiate" more than one of such object. The flip side
is that ONE "instance" is ALWAYS created and you can''t
control the lifetime of this "instance".

With Singleton, you have better control of when to create
and destroy the object. If you don''t use the Singleton,
then no instance is created.

Modern C++ Design has a chapter that details the many
varieties of Singletons.


~~~~
Kami no Itte ga ore ni zettai naru!

Share this post


Link to post
Share on other sites
Yes, you can do that. It''s what the singleton instance accessor does, anyway.

Why not make everything static? Because static objects do not have a guaranteed order of initialization. If you have one static object that depends on the existence of another, it might not work correctly (behavior is undefined). Using a singleton allows you to control exactly when the ctor fires.

Share this post


Link to post
Share on other sites