I’ve seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this:
SomeBaseClass &SomeClass::GetInstance() { static SomeClass instance; return instance; }
I see following positive sides of this approach:
- The code is simpler, because it’s compiler who responsible for creating this object only when GetInstance called for the first time.
- The code is safer, because there is no other way to get reference to instance, but with GetInstance method and there is no other way to change instance, but inside GetInstance method.
What are the negative sides of this approach (except that this is not very OOP-ish) ? Is this thread-safe?
In C++11 it is thread safe:
In C++03:
But this is because g++ explicitly adds code to guarantee it.
One problem is that if you have two singletons and they try and use each other during construction and destruction.
Read this: Finding C++ static initialization order problems
A variation on this problem is if the singleton is accessed from the destructor of a global variable. In this situation the singleton has definitely been destroyed, but the get method will still return a reference to the destroyed object.
There are ways around this but they are messy and not worth doing. Just don’t access a singleton from the destructor of a global variable.
A Safer definition but ugly:
I am sure you can add some appropriate macros to tidy this up