Is it possible to initialize the Instance of a Singleton when it is really needed?
Consider this pattern taken from the famous "Design Patterns":
class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
}
Singleton* Singleton::_instance = 0; // unit.cpp
static Singleton* Singleton::Instance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}
Now, I think there is a problem in the pattern there, if one desires to provide the Singleton in a library to others: if the user calls Singleton::Instance()
from another compilation unit (during a static data member initialization, for example) before _instance is initialized, then a following call of Singleton::Instance()
might create another instance of the Singleton, with unwanted results, since _instance might have been initialized to 0 first.
I think one solution is to initialize _instance this way:
Singleton* Singleton::_instance = Singleton::Instance();
Anyway, that makes the initialization not "lazy" for those who don't need to call Singleton::Instance() to initialize their static data.
Are there better solutions so that the inizialization can happen when the Singleton instance is needed?