Lazy initialization with singleton pattern

▼魔方 西西 提交于 2019-12-18 19:14:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!