单例创建和内存释放

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

posted @ 2013-08-18 17:03  bxddno1  阅读(3836)  评论(0编辑  收藏  举报