单例模式

class Singleton  
{
    public:
        static Singleton& Instance()
    {
        static Singleton instance;
        return instance;
    }
    private:
        Singleton();
        ~Singleton();
        Singleton(const Singleton&);
        Singleton& operator=(const Singleton&);
};

 采用effective c++中的方法,这里用到了static Singleton instance;这是一个local static对象,只有在第一次访问Instance()对象时候才会创建。注意这边将构造和析构函数都设为私有并且只声明,因此编译器不会在需要的时候自动再产生。

static Singleton& Instance()  
{
    if (instance_ == NULL) 
    {
        Lock lock; //基于作用域的加锁,超出作用域,自动调用析构函数解锁
        if (instance_ == NULL)
        {
              instance_ = new Singleton;
        }
    }
    return *instance_;
}

  双锁模式,线程安全。

via(http://www.zkt.name/dan-li-mo-shi-singleton-ji-c-shi-xian/) 

原文地址:https://www.cnblogs.com/rockwall/p/5788020.html