延遲初始化

這個例子已從 Q & A 部分解除了: http ://stackoverflow.com/a/1008289/3807729

有關使用保證破壞單例的惰性求值的簡單設計,請參閱此文章:
任何人都可以在 c ++中為我提供 Singleton 示例嗎?

經典的懶惰評估和正確銷燬的單例

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S() {};                   // Constructor? (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Dont forget to declare these two. You want to make sure they
        // are unacceptable otherwise you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
    public:
        S(S const&)               = delete;
        void operator=(S const&)  = delete;

        // Note: Scott Meyers mentions in his Effective Modern
        //       C++ book, that deleted functions should generally
        //       be public as it results in better error messages
        //       due to the compilers behavior to check accessibility
        //       before deleted status
};

請參閱此文章,瞭解何時使用單例:(不經常)
Singleton:如何使用它

請參閱這兩篇關於初始化順序以及如何應對的文章:
靜態變數初始化順序
查詢 C++靜態初始化順序問題

請參閱本文描述生命週期:
C++函式中靜態變數的生命週期是多少?

請參閱本文,討論對單例的一些執行緒影響:
Singleton 例項宣告為 GetInstance 方法的靜態變數

請參閱這篇文章,解釋為什麼雙重檢查鎖定在 C++上不起作用:
C++程式設計師應該知道的所有常見的未定義行為是什麼?