C++ 單例模式物件的創建於銷燬
阿新 • • 發佈:2019-01-10
關於單利模式的實現,網上的部落格很多,考慮到執行緒安全,以空間換時間等等,這裡我給出單利模式最簡單多執行緒全的實現,程式碼如下:
#include <iostream> using namespace std; class Singleton { public: static Singleton *GetInstance() { return m_Instance; } int GetTest() { return m_Test; } private: Singleton() { m_Test = 10; } static Singleton *m_Instance; int m_Test; //用內部類銷燬單例 class GC { public: ~GC() { // We can destory all the resouce here, eg:db connector, file handle and so on if (m_Instance != NULL) { cout << "Here is the test" << endl; delete m_Instance; m_Instance = NULL; } } }; static GC gc; }; Singleton *Singleton::m_Instance = new Singleton(); Singleton::GC Singleton::gc; //全域性物件,程式結束時會掉用它的解構函式 int main(int argc, char *argv[]) { Singleton *singletonObj = Singleton::GetInstance(); cout << singletonObj->GetTest() << endl; system("pause"); return 0; }
在程式執行結束時,系統會呼叫Singleton的靜態成員GC的解構函式,該解構函式會進行資源的釋放,而這種資源的釋放方式是在程式設計師“不知道”的情況下進行的,而程式設計師不用特別的去關心,使用單例模式的程式碼時,不必關心資源的釋放。那麼這種實現方式的原理是什麼呢?我剖析問題時,喜歡剖析到問題的根上去,絕不糊塗的停留在表面。由於程式在結束的時候,系統會自動析構所有的全域性變數,實際上,系統也會析構所有類的靜態成員變數,就像這些靜態變數是全域性變數一樣。我們知道,靜態變數和全域性變數在記憶體中,都是儲存在靜態儲存區的,所以在析構時,是同等對待的。