c++ 单例模式研究

一篇博文:C++ 单例模式的几种实现研究 中

看到的几段代码

懒汉模式

 1 class Singleton
 2 {
 3 public:
 4     static Singleton* GetInstance()
 5     {
 6         if (m_pInstance == NULL )
 7         {
 8             Lock(); // 加锁
 9             if (m_pInstance == NULL )
10             {
11                 m_pInstance = new Singleton ();
12             }
13             UnLock(); // 解锁
14         }
15         return m_pInstance;
16     }
17 
18     // 实现一个内嵌垃圾回收类    
19     class CGarbo 
20     {
21     public:
22         ~CGarbo()
23         {
24             if(Singleton::m_pInstance) 
25                 delete Singleton::m_pInstance;
26         }
27     };
28 
29     static CGarbo Garbo; // 定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数从而释放单例对象
30 
31 private:
32     Singleton(){};
33     Singleton(Singleton const&); 
34     Singleton& operator=(Singleton const&); 
35 
36     static Singleton* m_pInstance;
37 };
38 
39 Singleton* Singleton::m_pInstance = NULL;
40 Singleton::CGarbo Garbo;

c++11以上

 1 class Singleton
 2 {
 3 public:
 4     static Singleton* GetInstance()
 5     {
 6         Lock(); // not needed after C++0x 
 7         static Singleton instance;  
 8         UnLock(); // not needed after C++0x 
 9 
10         return &instance;
11     }
12 
13 private:
14     Singleton() {};
15     Singleton(const Singleton &);
16     Singleton & operator = (const Singleton &);
17 };

饿汉模式

 1 class Singleton
 2 {
 3 public:
 4     static Singleton* GetInstance()
 5     {
 6         static Singleton instance;
 7         return &instance;
 8     }
 9 
10 protected:
11     // 辅助代理类
12     struct Object_Creator
13     {
14         Object_Creator()
15         {
16             Singleton::GetInstance();
17         }
18     };
19     static Object_Creator _object_creator;
20 
21     Singleton() {}
22     ~Singleton() {}
23 };
24 
25 Singleton::Object_Creator Singleton::_object_creator;

解决跨编译单元的初始化顺序,即A生成依赖B,但是先生成A还生成B不能确定

如果没有这种需求基础的饿汉就可以

关于使用懒汉还是饿汉模式,博主的理解:

如果这个单例对象构造十分耗时或者占用很多资源,比如加载插件啊, 初始化网络连接啊,读取文件啊等等,而有可能该对象程序运行时不会用到,那么也要在程序一开始就进行初始化,也是一种资源浪费吧。 所以这种情况懒汉模式(延迟加载)更好。

如果这个单例对象在多线程高并发环境下频繁使用,性能要求较高,那么显然使用饿汉模式来避免资源竞争,提高响应速度更好。

从中我们可以看到的是性能需求,我们用c++的需求应该就是从性能出发。所以当对对象性能要求不高时,懒汉模式推荐;性能要求高时,饿汉模式推荐。

原文地址:https://www.cnblogs.com/lmaster/p/10521264.html