问题
Would the following code facilitate lazy initialization?
Or would the singletonInstance
be created as soon as somebody includes the header (or even at program startup time)?
class SingletonClass
{
private:
SingletonClass();
~SingletonClass();
public:
static const SingletonClass& Instance()
{
static SingletonClass singletonInstance;
return singletonInstance;
}
};
回答1:
This is known as the Meyers singleton and they are lazy instantiated.
There are some considerations:
- the singletons will be destroyed at the end of the program in the reverse order in which they are created, so there can be dependency issues.
- C++03 doesn't guarantee against race conditions in multithreaded environments.
回答2:
The SingletonClass
constructor will not be called earlier than somenone calls the Instance()
method.
Thus yes, it facilitates lazy initialization.
来源:https://stackoverflow.com/questions/21252296/lazy-initialization-with-singleton-pattern