c++ 單例模式研究

一篇博文:C++ 單例模式的幾種實現研究 中html

看到的幾段代碼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不能肯定函數

若是沒有這種需求基礎的餓漢就能夠高併發

 

關於使用懶漢仍是餓漢模式,博主的理解:post

若是這個單例對象構造十分耗時或者佔用不少資源,好比加載插件啊, 初始化網絡鏈接啊,讀取文件啊等等,而有可能該對象程序運行時不會用到,那麼也要在程序一開始就進行初始化,也是一種資源浪費吧。 因此這種狀況懶漢模式(延遲加載)更好。性能

若是這個單例對象在多線程高併發環境下頻繁使用,性能要求較高,那麼顯然使用餓漢模式來避免資源競爭,提升響應速度更好。url

 

從中咱們能夠看到的是性能需求,咱們用c++的需求應該就是從性能出發。因此當對對象性能要求不高時,懶漢模式推薦;性能要求高時,餓漢模式推薦。

相關文章
相關標籤/搜索