延迟初始化

这个例子已从 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++程序员应该知道的所有常见的未定义行为是什么?