单例模式,其核心目标是确保在程序运行的过程中,有且只有存在一个实例才能保证他们的逻辑正确性以及良好的效率。因此单例模式的实现思路就是确保一个类有且只有一个实例,并提供一个该实例的全局访问点。 单例模式设计要点:
除了上面提到的四点还要注意线程安全以及资源释放的问题。
本文从最基本的懒汉式和饿汉式单例模式开始,循序渐进地讨论单例模式形式的特点及变化过程
饿汉式单例模式的核心思路就是不管需不需要用到实例都要去创建实例。饿汉模式的实例在类产生时候就创建了,它的生存周期和程序一样长。
对于饿汉模式而言,是线程安全的,因为在线程创建之前唯一的实例已经被创建好了。而且在程序的退出阶段,类内唯一实例instance也会被销毁,~CSingleton会被调用,资源可以正常被释放。
instance
~CSingleton
//无延迟初始化//多线程安全,资源自动释放class CSingleton{public: static CSingleton* getInstance();private: CSingleton(){std::cout<<"创建了一个对象"<<std::endl;} ~CSingleton(){std::cout<<"销毁了一个对象"<<std::endl;} CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete; static CSingleton instance; //将指针改为普通的变量}; CSingleton CSingleton::instance;CSingleton* CSingleton::getInstance(){ return &instance;}//测试代码,后面不赘述int main(){ std::cout << "Now we get the instance" << std::endl; std::thread t1([](){auto instance = CSingleton::getInstance();}); std::thread t2([](){auto instance = CSingleton::getInstance();}); std::thread t3([](){auto instance = CSingleton::getInstance();}); t1.join(); t2.join(); t3.join(); std::cout << "Now we destroy the instance" << std::endl; return 0;}
//无延迟初始化
//多线程安全,资源自动释放
class CSingleton
{
public:
static CSingleton* getInstance();
private:
CSingleton(){std::cout<<"创建了一个对象"<<std::endl;}
~CSingleton(){std::cout<<"销毁了一个对象"<<std::endl;}
CSingleton(const CSingleton&) = delete;
CSingleton& operator=(const CSingleton&) = delete;
static CSingleton instance; //将指针改为普通的变量
};
CSingleton CSingleton::instance;
CSingleton* CSingleton::getInstance()
return &instance;
}
//测试代码,后面不赘述
int main()
std::cout << "Now we get the instance" << std::endl;
std::thread t1([](){auto instance = CSingleton::getInstance();});
std::thread t2([](){auto instance = CSingleton::getInstance();});
std::thread t3([](){auto instance = CSingleton::getInstance();});
t1.join();
t2.join();
t3.join();
std::cout << "Now we destroy the instance" << std::endl;
return 0;
测试结果:
饿汉式的缺点:
与饿汉式单例模式相比,懒汉式的关键区别在于它延迟了单例实例的创建,即直到第一次被使用时才创建实例:
//延迟初始化//多线程不安全,资源无法自动释放class CSingleton{public: static CSingleton* getInstance();private: CSingleton(){std::cout<<"创建了一个对象"<<std::endl;} ~CSingleton(){std::cout<<"销毁了一个对象"<<std::endl;} CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete; static CSingleton* instance; };CSingleton* CSingleton::instance; CSingleton* CSingleton::getInstance(){ if(nullptr == instance) instance = new CSingleton(); return instance;}
//延迟初始化
//多线程不安全,资源无法自动释放
static CSingleton* instance;
CSingleton* CSingleton::instance;
if(nullptr == instance)
instance = new CSingleton();
return instance;
但是上述代码有几个缺点:
为了解决线程安全的问题,下面讨论加锁的懒汉式单例模式:
为了让懒汉式做到线程安全,我们首先会想到加锁:
class CSingleton{public: ... static std::mutex mtx;private: ...};CSingleton* CSingleton::instance; std::mutex CSingleton::mtx; CSingleton* CSingleton::getInstance(){ mtx.lock(); if(nullptr == instance) { instance = new CSingleton(); } mtx.unlock(); return instance;}
...
static std::mutex mtx;
std::mutex CSingleton::mtx;
mtx.lock();
mtx.unlock();
但是要注意,加锁和解锁的操作是需要时间的,上述方法在多线程的情况下,每次调用都会浪费时间在上锁和解锁上,导致效率下降。其实我们真正需要的,只是在instance 初始化时上锁保证线程安全,即只有getInstance()第一次被调用时上锁才是必要的。若在程序中,getInstance()被调用了n次,那么只有第一次调用锁是起真正作用的,其余n-1次做操作都是没必要的。
getInstance()
所以要想改进上述问题,我们在加锁之前先判个空,当判断结果为真(即instance还没有被初始化),才进行加锁操作,然后再次检查instance是否为空。
//双检查锁模式DCLPCSingleton* CSingleton::getInstance(){ if (nullptr == instance) { mtx.lock(); if(nullptr == instance) { instance = new CSingleton(); } mtx.unlock(); } return instance;}
//双检查锁模式DCLP
if (nullptr == instance)
第二次检查必不可少,这是因为在第一次检查instance 和加锁之间,可能会有别的线程对instance 进行初始化。
但是遗憾的是,这种方法其实也不是线程安全的,具体原因可见:补充-指令重排
其实,使用了DCLP的懒汉式单例模式不但线程不安全,而且无法通过RAII机制调用析构函数释放相关资源。具体原因可见:补充-单例模式析构
为了解决线程安全问题和资源释放问题,Scott Meyers提出了局部静态变量形式的单例模式。
这种形式的单例模式使用函数中的局部静态变量来代替类中的静态成员指针:
//延迟初始化//多线程安全,资源自动释放class CSingleton{private: CSingleton() {std::cout << "创建了一个对象" << std::endl;} ~CSingleton() {std::cout << "销毁了一个对象" << std::endl;} CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete;public: static CSingleton& getInstance() { static CSingleton instance; return instance; }};//测试代码int main(){ std::cout << "Now we get the instance" << std::endl; std::thread t1([](){auto& instance = CSingleton::getInstance();}); std::thread t2([](){auto& instance = CSingleton::getInstance();}); std::thread t3([](){auto& instance = CSingleton::getInstance();}); t1.join(); t2.join(); t3.join(); std::cout << "Now we destroy the instance" << std::endl; return 0;}
CSingleton() {std::cout << "创建了一个对象" << std::endl;}
~CSingleton() {std::cout << "销毁了一个对象" << std::endl;}
static CSingleton& getInstance()
static CSingleton instance;
//测试代码
std::thread t1([](){auto& instance = CSingleton::getInstance();});
std::thread t2([](){auto& instance = CSingleton::getInstance();});
std::thread t3([](){auto& instance = CSingleton::getInstance();});
对于线程安全问题:在C++11及更高版本中,静态局部变量的初始化是线程安全的。即当多个线程同时首次访问局部静态变量,编译器可以保证其初始化代码仅执行一次,防止了任何可能的竞态条件或重复初始化。
对于资源释放问题:代码中局部静态变量instance的生命周期开始于第一次调用getInstance方法时,终止于程序结束时。在程序的退出阶段局部静态变量instance被销毁,~CSingleton被调用,确保了资源的正确释放。
getInstance
在大型项目中,如果有多个类都被设计为要具有单例行为,那么为了方便这些类的创建,我们可以将单例属性封装为一个模板类,在需要时继承这个模板基类,这样这些子类就可以继承它的单例属性。
因为这种单例模式是基于静态局部变量的,所以它是多线程安全的而且是可以正常进行资源释放的:
template <typename T>class CSingleton {protected: CSingleton(){std::cout<<"创建了一个对象"<<std::endl;} ~CSingleton(){std::cout<<"销毁了一个对象"<<std::endl;} CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete;public: static T& getInstance() { static T instance; return instance; }};//使用模板class MyClass : public CSingleton<MyClass>{ friend class CSingleton<MyClass>;private: MyClass(){std::cout<<"this is MyClass construct"<<std::endl;} ~MyClass(){std::cout<<"this is MyClass destruct"<<std::endl;}public: void dosomething() { std::cout<<"dosomething"<<std::endl; }};
template <typename T>
protected:
static T& getInstance()
static T instance;
//使用模板
class MyClass : public CSingleton<MyClass>
friend class CSingleton<MyClass>;
MyClass(){std::cout<<"this is MyClass construct"<<std::endl;}
~MyClass(){std::cout<<"this is MyClass destruct"<<std::endl;}
void dosomething()
std::cout<<"dosomething"<<std::endl;
这种形式使用了奇异递归模板模式(Curiously Recurring Template Pattern, CRTP)。在使用时要注意,子类需要将自己作为模板参数传递给CSingleton模板进行模板类实例化,用做基类;同时需要将基类声明为友元,这样才能在通过CSingleton<T>::getInstance()方法创建MyClass唯一实例时,调用到MyClass的私有构造函数。
CSingleton<T>::getInstance()
1.C++ 单例模式
原文链接:https://www.cnblogs.com/paw5zx/p/18081803
本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728