简体   繁体   中英

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 ? I don't see any new 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. Before C++11, this is not thread-safe (however, certain compilers do offer options to enforce thread-safe). 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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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