简体   繁体   English

需要帮助来了解单例模式

[英]Need help on understanding a singleton pattern

can someone explain me this code? 有人可以向我解释此代码吗?

class S
{
    public:
      static S& getInstance()
        {
            static S    instance;
            return instance;
        }
    private:
        S() {}
        S(S const&);              // Don't Implement.
        void operator=(S const&); // Don't implement
};

What I understood is : getInstance is a static method that will return a reference to the instance, but where is this instance created ? 我了解的是:getInstance是一个静态方法,它将返回对该实例的引用,但是该实例在哪里创建的? I don't see any new S(); 我没有看到任何新的S(); so.. 所以..

A block-scope entity with static storage duration (in your case the static S instance; ) is initialized the first time control passes through its declaration. 具有静态存储持续时间(在您的情况下为static S instance; )的块作用域实体在控件第一次通过其声明时被初始化。 Before C++11, this is not thread-safe (however, certain compilers do offer options to enforce thread-safe). 在C ++ 11之前,这不是线程安全的(但是,某些编译器确实提供了强制执行线程安全的选项)。 As for C++11, the standard states that "If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization." 对于C ++ 11,标准指出“如果在初始化变量时控件同时输入声明,则并发执行应等待初始化完成。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM