singleton question

closed account (zwA4jE8b)
I never really understood singletons but I think I've got it.

The static initialization allows for only 'one' instance to exist.
because static parts of classes are global across all instances of the class.

is that correct? or at least somewhat correct.
Last edited on
Yes and no. The singleton pattern programmatically enforces the rule that there can be at most one instance of a class at any given time. This is done by hiding the constructor (making it private), declaring the copy constructor and assignment operator private and leaving them unimplemented, hiding the destructor (private), then providing a static "getInstance" method that either constructs a new instance if no instances already exist, or returns a reference to the one instance already created.

Making all data members of a class static is an ersatz singleton pattern, in that I can still have N "instances" of the object, it's just that all instances operate on the same data (meaning that all instances change in lock-step).
closed account (zwA4jE8b)
thank you.
Topic archived. No new replies allowed.