(原创,转载注明出处: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 )