单例模式的实现--C++
2021/10/7 11:12:51
本文主要是介绍单例模式的实现--C++,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
实现单例模式 只能生成一个实例的类是实现了单例模式的类型 //(1)只适合单线程环境的的单例模式实现 class Singleton final { private: Singleton() {}; ~Singleton() {}; Singleton(const Singleton&) {}; Singleton& operator=(const Singleton&) {}; private: static Singleton* instance; public: static Singleton* Instance() { if (instance == nullptr) //这个地方多线程是时候有可能出现错误。 { instance = new Singleton(); } return instance; }; }; Singleton* Singleton::instance = nullptr; //以上的范例只适合在单线程下操作,如果在多线程中多个线程同时运行到判断instance //是否为nullptr的if语句,并且instance的确没有创建时,那么多个线程都会创建一个 //一个实例,此时类型Singleton就不再满足单例模式的需求了。且此类型Singleton的写法 //会存在内存泄露的问题。 //针对内存泄露的问题,我们有以下两种解决方法。 //(1.1)解决内存泄露的第一种方式:智能指针解决内存泄露问题 #include<memory> using namespace std; class Singleton final { private: Singleton() {}; ~Singleton() {}; Singleton(const Singleton&) {}; Singleton& operator=(const Singleton&) {}; private: static shared_ptr<Singleton> instance; public: static shared_ptr<Singleton> Instance() { if (instance == nullptr) //这个地方多线程是时候有可能出现错误。 { instance = make_shared<Singleton>(); } return instance; }; }; shared_ptr<Singleton> Singleton::instance = nullptr; //将instance定义为智能指针的形式,则不会出现内存泄露的问题。 //(1.2) 解决内存泄露的第二种方式,利用类中类和静态成员结合的方式 class Singleton final { private: Singleton() {}; ~Singleton() {}; Singleton(const Singleton&) {}; Singleton& operator=(const Singleton&) {}; private: static Singleton* instance; private: class Deletor { public: ~Deletor() { if (Singleton::instance != nullptr) { delete Singleton::instance; Singleton::instance = nullptr; } } }; static Deletor deletor; public: static Singleton* Instance() { if (instance == nullptr) //这个地方多线程是时候有可能出现错误。 { instance = new Singleton(); } return instance; }; }; Singleton* Singleton::instance = nullptr; //这样在程序运行结束的时候,会调用deletor的析构函数, //该函数会删除单例的唯一的实例。
这篇关于单例模式的实现--C++的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升