from:http://www.pconline.com.cn/pcedu/empolder/gj/c/0407/421424.html
ANSI C++ 中的 Singleton 實(shí)現(xiàn)說難不難,說容易也不容易,很多人寫 ANSI C++ 的 Singleton class 都有錯(cuò)誤。這篇文章討論怎樣在 ANSI c++ 中寫 Singleton class, 希望對(duì)大家有幫助。
? 《設(shè)計(jì)模式》中把 Singleton 寫成返回指針:
| class Singleton{ public: ??? static Singleton* Instance(); protected: ??? Singleton(); private: ??? static Singleton* _instance; }; |
????? 相應(yīng)的實(shí)現(xiàn) cpp 文件是:
| Singleton* Singleton::_instance; Singleton* Singleton::Instance(){ ??? if( _instance == 0){ ??????? _instance = new Singleton; ??? }; ??? return _instance; } |
?
???
將構(gòu)造函數(shù)設(shè)計(jì)成 protected 的目的是防止在 class 外面 new ,有人可能會(huì)設(shè)計(jì)成 private
,如果考慮到有可能會(huì)繼承這個(gè)類的話,還是將構(gòu)造函數(shù)設(shè)計(jì)成 protected 比較好,還需要加一個(gè) virtual 析構(gòu)函數(shù)。為了防止別人復(fù)制
Singleton 對(duì)象:
| Singleton* pSingleton = Singleton::Instance(); Singleton s1 = *pSingleton; Singleton s2 = *pSingleton; 需要將拷貝構(gòu)造(copy constructor)函數(shù)變成 private。 |
???
但是這里存在的問題是,什么時(shí)候刪除 Singleton 對(duì)象?按照 C++ 的一個(gè)基本原則,對(duì)象在哪里創(chuàng)建就在哪里銷毀,這里還應(yīng)該放一個(gè)
destroy 方法來刪除 Singleton 對(duì)象。如果忘了刪除就比較麻煩。Instance 函數(shù)還存在多線程同時(shí)訪問的加鎖問題。如果把
Instance 函數(shù)開始和結(jié)尾放上加鎖和解鎖,整個(gè)函數(shù)性能會(huì)下降很多。這不是一個(gè)好的設(shè)計(jì)。
??? 有一個(gè)小小的改動(dòng),可以避免忘了刪除
Singleton 對(duì)象帶來內(nèi)存泄露的問題。那就是用 std:auto_ptr 來包含 Singleton 對(duì)象,定義一個(gè)class
static member auto_ptr 對(duì)象,在析構(gòu)的靜態(tài) auto_ptr 變量的時(shí)候時(shí)候自動(dòng)刪除 Singleton
對(duì)象。為了不讓用戶 delete Singleton 對(duì)象,需要將析構(gòu)函數(shù)由 public 變成 protected。以下是頭文件
SingletonAutoPtr.h :
| #include <memory> using namespace std; class CSingletonAutoPtr { private: ??? static auto_ptr<CSingletonAutoPtr> m_auto_ptr; |