DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

C++: 单例模式和缺陷

 

实现一个单例模式

1 class Singleton {
2     private:
3         Singleton() { cout << "Singleton::constructor" << endl; }
4         ~Singlton() { cout << "Singleton::destructor" << endl; }
5         Singleton(const Singleton&) {};
6         Singleton &operator=(const Singleton&) {};
7     public:
8         static Singleton* getInstance() {
9             if(m_aInstance == NULL) {
10                 m_aInstance = new Singleton();
11             }
12             return m_aInstance;
13         }
14         void show() {
15             cout << "Singleton::show" << endl;
16         }
17     private:
18         static Singleton* m_aInstance;
19 };
20  
21 Singleton* Singleton::m_aInstance = NULL;
22  
23 int main(int argc, char **argv) {
24     Singleton* aSingleton = Singleton::getInstance();
25     aSingleton->show();
26     return 0;
27 }
编译执行上面的代码,输出如下:

 

Singleton::constructor
Singleton::show
我们发现上面的输出并没有调用到Singleton的虚构函数,Singleton的资源可能没有被释放。现在的问题是要怎么才能在程序退出的时候正确释放Singleton的资源。我们注意到这样一个事实:

 

系统会自动调用在栈和静态数据区上分配的对象的析构函数来释放资源。

修改程序如下:

1 class Singleton {
2     private:
3         Singleton() { cout << "Singleton::constructor" << endl; }
4         ~Singleton() { cout << "Singleton::destructor" << endl; }
5         Singleton(const Singleton&) {};
6         Singleton &operator=(const Singleton&) {};
7     public:
8         static Singleton* getInstance() {
9             if(m_aInstance == NULL) {
10                 m_aInstance = new Singleton();
11             }
12             return m_aInstance;
13         }
14         void show() {
15             cout << "Singleton::show" << endl;
16         }
17  
18     private:
19         class Garbage{
20             public:
21                 ~Garbage() {
22                     if(m_aInstance != NULL) {
23                         delete m_aInstance;
24                     }
25                 }
26         };
27      
28     private:
29         static Singleton* m_aInstance;
30         static Garbage m_garbage;
31 };
32  
33 Singleton* Singleton::m_aInstance = NULL;
34 Singleton::Garbage Singleton::m_garbage;
35  
36 int main(int argc, char **argv) {
37     Singleton* aSingleton = Singleton::getInstance();
38     aSingleton->show();
39     return 0;
40 }
编译上面的代码并执行,输出如下:

 

Singleton::constructor
Singleton::show
Singleton::destructor

我们看到Singleton::destructor被明确的执行了。

posted on   DoubleLi  阅读(1111)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示