提起单例,面试中几乎是必问的问题,单例的实现方式,也包含多种(饿汉模式和懒汉模式,单锁、双检查锁机制等)。
    由于C++11及以后的版本中,静态变量初始化是线程安全。
    
    写法如下:
   
class Singleton{
public:
    static Singleton& getInstance(){
        static Singleton m_instance;  //局部静态变量
        return m_instance;
    }
    Singleton(const Singleton& other) = delete;
    Singleton& operator=(const Singleton& other) = delete;
protected:
    Singleton() = default;
    ~Singleton() = default;
};
    备注:
    
    拷贝构造函数和赋值构造函数设置为delete。避免对象被再次构造或者拷贝。
    
    利用模板实现单例:
   
template<typename T>
class Singleton
{
public:
    static T& getInstance() {
        static T t;
        return t;
    }
    Singleton(const Singleton&) = delete; 
    Singleton& operator=(const Singleton&) = delete; 
protected:
    Singleton() = default;
    ~Singleton() = default;
};
模板单例使用:
class MySingleon:public Singleton<MySingleon>
{
public:
    void myTest()
    {
        std::cout<<"mySingleton"<<std::endl;
    }
};
int main()
{
    MySingleon::getInstance().myTest();
    return 0;
}
另一种简单使用方法:
class MySingleon
{
public:
    void myTest()
    {
        std::cout<<"MySingleon"<<std::endl;
    }
};
int main()
{
    Singleton<MySingleon>::getInstance().myTest();
    return 0;
}
 
版权声明:本文为qqzhaojianbiao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。