單例創建和內存釋放


(原創,轉載注明出處:http://www.cnblogs.com/binxindoudou/p/3261082.html )

c++的單例創建和內存釋放

c++的單例模式的使用實例,在網上有很多,但是我發現卻很少有例子去考慮這個單例的內存管理的問題。單例本身是在堆區分配的空間,所以需要在不使用的時候進行釋放。

static CppSingleton* m_singleInstance;

可是什么時候釋放這個單例,就是個問題,因為或許在整個程序生命過程中都需要使用這個單例來進行數據保存和傳遞,而不是你需要手動釋放的,所以姑且認為單例就是隨着程序的生死而生死的吧(當然有例外的情況,比如有的單例只在該模塊中數據保存和釋放,所以模塊被換掉,單例就失去意義了,這個需要你手動釋放的,在這里不考慮這個情況先)

那么我們要做的就是程序結束的時間點來進行單例的內存釋放。

先上代碼吧

CppSingleton.h

 1 //  2 // CppSingleton.h  3 // singletonMemoryRelease  4 //  5 // Created by admin on 13-8-15.  6 //  7 //  8  9 #ifndef __CPPSINGLETON_H__ 10 #define __CPPSINGLETON_H__ 11 12 #include <iostream> 13 14 using namespace std; 15 16 class CppSingleton 17 { 18 public: 19 static CppSingleton* sharedSingleInstance(); 20 ~CppSingleton(); 21 //The class will be use the by the CppSingleton 22 //The work of the class is to release the singleton 23 class SingletonGarbo 24  { 25 public: 26 ~SingletonGarbo() 27  { 28 cout << "Singleton Garbo distructor is called." << endl; 29 if(m_singleInstance) 30  { 31  delete m_singleInstance; 32  } 33  } 34  }; 35 private: 36 //You must use the private constructor to make sure that user can user the m_singleInstance by calling the sharedSingleInstance() 37  CppSingleton(); 38 static CppSingleton* m_singleInstance; 39 //When the program ends,the global and the static variable will be release 40 static SingletonGarbo garbo; 41 }; 42 43 #endif

CppSingleton.cpp

 1 //  2 // CppSingleton.cpp  3 // singletonMemoryRelease  4 //  5 // Created by admin on 13-8-15.  6 //  7 //  8  9 #include "CppSingleton.h" 10 11 CppSingleton* CppSingleton::m_singleInstance = NULL; 12 CppSingleton::SingletonGarbo garbo; 13 14 CppSingleton* CppSingleton::sharedSingleInstance() 15 { 16 if(m_singleInstance == NULL) 17  { 18 m_singleInstance = new CppSingleton(); 19  } 20 return m_singleInstance; 21 } 22 23 CppSingleton::~CppSingleton() 24 { 25 cout << "The distructor is called." << endl; 26 } 27 28 CppSingleton::CppSingleton() 29 { 30 cout << "The constructor is called." << endl; 31 }

在這個里邊的使用的原理就是棧區靜態變量或者全局變量初始化和銷毀是系統自動執行的,分別發生在程序編譯的時候和程序結束運行的時候

那么在.h文件中的嵌套類(防止其他類的使用)SingletonGarbo做的就是這個工作,聲明一個靜態的變量---static SingletonGarbo garbo(垃圾工人)

注意:我在使用的過程中以為只在頭文件中寫入static SingletonGarbo garbo;就可以進行初始化,可是卻怎么也得不到這個垃圾工人的初始化,構造函數不會執行,需要在cpp文件中初始化才行。以后靜態變量,不管是堆區還是棧區的,在h文件中只做聲明的工作,在cpp中才會初始化。

然后這個棧區的垃圾工人就會在程序運行之前分配內存和初始化,在程序結束的時候自動銷毀,那么就可以在自動銷毀的這個事件里(析構函數)進行這個單例的釋放,實現了,隨着程序結束的釋放而釋放。

(原創,轉載注明出處:http://www.cnblogs.com/binxindoudou/p/3261082.html )


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM