单例模式 看这个 大全

https://www.cnblogs.com/sunchaothu/p/10389842.html

最推荐的懒汉式单例(magic static )——局部静态变量

#include <iostream>

class Singleton
{
public:
    ~Singleton(){
        std::cout<<"~Singleton()"<<std::endl;
    }
    Singleton(const Singleton&)=delete;
    Singleton& operator=(const Singleton&)=delete;
    static Singleton& getInstance(){
        static Singleton instance;
        return instance;
    }
private:
    Singleton(){
        std::cout<<"Singleton()"<<std::endl;
    }
};

int main(int argc, char *argv[])
{
    Singleton& instance_1 = Singleton::get_instance();
    Singleton& instance_2 = Singleton::get_instance();
    return 0;
}

运行结果

constructor called!
destructor called!

这种方法又叫做 Meyers' SingletonMeyer's的单例, 是著名的写出《Effective C++》系列书籍的作者 Meyers 提出的。所用到的特性是在C++11标准中的Magic Static特性:

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
如果当变量在初始化的时候,并发同时进入声明语句,并发线程将会阻塞等待初始化结束。

这样保证了并发线程在获取静态局部变量的时候一定是初始化过的,所以具有线程安全性。

C++静态变量的生存期 是从声明到程序结束,这也是一种懒汉式。

这是最推荐的一种单例实现方式:

    1. 通过局部静态变量的特性保证了线程安全 (C++11, GCC > 4.3, VS2015支持该特性);
    2. 不需要使用共享指针,代码简洁;
    3. 注意在使用的时候需要声明单例的引用 Single& 才能获取对象。
原文地址:https://www.cnblogs.com/WHUT-Simon/p/11801693.html