1. 程式人生 > >C++單例模式 正確的資源回收方式

C++單例模式 正確的資源回收方式

C++的懶漢和餓漢實現模式:點選開啟連結

關於C++單例模式下m_pinstance指向空間銷燬問題,m_pInstance的手動銷燬經常是一個頭痛的問題,記憶體和資源洩露也是屢見不鮮,能否有一個方法,讓例項自動釋放。

解決方法就是定義一個內部垃圾回收類,並且在Singleton中定義一個此類的靜態成員。程式結束時,系統會自動析構此靜態成員,此時,在此類的解構函式中析構Singleton例項,就可以實現m_pInstance的自動釋放。

附上測試程式碼

複製程式碼
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Singleton
5 { 6 public: 7 static Singleton *GetInstance() 8 { 9 if (m_Instance == NULL) 10 { 11 m_Instance = new Singleton(); 12 cout<<"get Singleton instance success"<<endl; 13 } 14 return m_Instance; 15 } 16 17 private: 18 Singleton(){cout<<"
Singleton construction"<<endl;} 19 static Singleton *m_Instance; 20 21 // This is important 22 class GC // 垃圾回收類 23 { 24 public: 25 GC() 26 { 27 cout<<"GC construction"<<endl; 28 } 29 ~GC() 30 { 31 cout<<"
GC destruction"<<endl; 32 // We can destory all the resouce here, eg:db connector, file handle and so on 33 if (m_Instance != NULL) 34 { 35 delete m_Instance; 36 m_Instance = NULL; 37 cout<<"Singleton destruction"<<endl; 38 system("pause");//不暫停程式會自動退出,看不清輸出資訊 39 } 40 } 41 }; 42 static GC gc; //垃圾回收類的靜態成員 43 44 }; 45 46 Singleton *Singleton::m_Instance = NULL; 47 Singleton::GC Singleton::gc; //類的靜態成員需要類外部初始化,這一點很重要,否則程式執行連GC的構造都不會進入,何談自動析構 48 int main(int argc, char *argv[]) 49 { 50 Singleton *singletonObj = Singleton::GetInstance(); 51 return 0; 52 }
複製程式碼


執行結果: