C++ 线程安全的单例模式

您所在的位置:网站首页 c++线程安全的几种方法 C++ 线程安全的单例模式

C++ 线程安全的单例模式

2022-10-06 11:15| 来源: 网络整理| 查看: 265

returninstance_; }

~Singleton = default;

// 释放资源。voidDestroy{ if(instance_ != nullptr) { deleteinstance_; instance_ = nullptr; }}

voidPrintAddressconst{ std:: coutPrintAddress;

return0; }

3. 懒汉模式优化

上述代码有一个问题,当程序使用完该单例,需要手动去调用Destroy来释放该单例管理的资源。如果不去手动释放管理的资源(例如加载的文件句柄等),虽然程序结束会释放这个单例对象的内存,但是并没有调用其析构函数去关闭这些管理的资源句柄等。解决办法就是将该管理的对象用智能指针管理。代码如下:

classSingleton{ public: staticSingleton& GetInstance{ if(!instance_) { std::lock_guard< std::mutex> lock(mutex_); if(!instance_) { instance_.reset( newSingleton); }}

return*instance_; }

~Singleton = default;

voidPrintAddressconst{ std:: cout



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3