關於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 }
運行結果:

