單例建立和內存釋放

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

c++的單例建立和內存釋放ios

c++的單例模式的使用實例,在網上有不少,可是我發現卻不多有例子去考慮這個單例的內存管理的問題。單例自己是在堆區分配的空間,因此須要在不使用的時候進行釋放。c++

static CppSingleton* m_singleInstance;函數

但是何時釋放這個單例,就是個問題,由於或許在整個程序生命過程當中都須要使用這個單例來進行數據保存和傳遞,而不是你須要手動釋放的,因此姑且認爲單例就是隨着程序的生死而生死的吧(固然有例外的狀況,好比有的單例只在該模塊中數據保存和釋放,因此模塊被換掉,單例就失去意義了,這個須要你手動釋放的,在這裏不考慮這個狀況先)spa

那麼咱們要作的就是程序結束的時間點來進行單例的內存釋放。code

先上代碼吧htm

CppSingleton.hblog

 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 )

相關文章
相關標籤/搜索