I have been reading a lot about Singletons, when they should and shouldn't be used, and how to implement them safely. I am writing in C++11, and have come across the Meyer's lazy initialized implementation of a singleton, as seen in this question.
This implementation is:
static Singleton& instance() { static Singleton s; return s; } I understand how this is thread safe from other questions here on SO, but what I don't understand is how this is actually a singleton pattern. I have implemented singletons in other languages, and these always end up something like this example from Wikipedia:
public class SingletonDemo { private static volatile SingletonDemo instance = null; private SingletonDemo() { } public static SingletonDemo getInstance() { if (instance == null) { synchronized (SingletonDemo .class){ if (instance == null) { instance = new SingletonDemo (); } } } return instance; } } When I look at this second example, it is very intuitive how this is a singleton, since the class holds a reference to one instance of itself, and only ever returns that instance. However, in the first example, I don't understand how this prevents there ever existing two instances of the object. So my questions are:
- How does the first implementation enforce a singleton pattern? I assume it has to do with the static keyword, but I am hoping that someone can explain to me in depth what is happening under the hood.
- Between these two implementation styles, is one preferable over the other? What are the pros and cons?
Thanks for any help,
static Singleton s;means the first time the function is called this variable will be initialized and unlike non-static variables it will not be destroyed once the function ends. So when you call it again it will still exist so the only instruction that will be executed the 2nd (3rd, 4th, ...) time is return s.Singleton's constructor is private, so the only way to actually obtain an instance is viainstance()function.statickeyword, is a perfectly valid question, too. This cannot just be the singleton-haters screaming for blood. Seriously, I am one of those, too, but neither does this make this question invalid. +1