单例对象释放问题

/*
class A
{};
A a;
单例模式就是全局只有一个类A产
生的对象不允许产生多个对象。






1.static成员变量实现了同类对象间信息共享
2.static成员类外存储,求类大小,并不包含在内
3.static成员是命名空间属于累的全局变量,存储在data区
4.static成员只能类外初始化
5.可以通过类名访问(无对象生成时亦可),也可以通过对象访问
*/
# include <iostream>


using namespace std;


class A
{
private:
A()
{
a = new A;
}
public:
static A* getInstace()
{
return a;
}
private:
static A* a;
};


A* A::a = NULL;


//实现单例步骤
//1.构造函数私有化
//2.增加静态类私有的当前类的指针变量
//3.提供静态对外接口,可以让用户获得单例对象


//单例 分为懒汉式 饿汉式
/*
饿汉式的特点是一开始就加载了,如果说懒汉
式是“时间换空间”,那么饿汉式就是“空间换
时间”,因为一开始就创建了实例,所以每次
用到的之后直接返回就好了
*/
//懒汉式
class Singleton_lazy
{
private:
Singleton_lazy()
{
cout << "我是懒汉式构造" << endl;
}
public:
static Singleton_lazy* getInstance()
{
if(pSingleton == NULL)
{
pSingleton = new Singleton_lazy;
}
return pSingleton;
}
# if 0
//推荐不要增加这个功能,因为是单例模式如果释放了
//就没了,全局就这一个变量。
static void freeSpace()
{
if(pSingleton != NULL)
{
delete pSingleton;
}
}
# endif
private:
static Singleton_lazy* pSingleton;
};
//类外初始化
Singleton_lazy* Singleton_lazy::pSingleton = NULL;








//饿汉式
class Singleton_hungry
{
private:
Singleton_hungry()
{
cout << "我是饿汉构造" << endl;
}
public:
static Singleton_hungry* getInstance()
{
return pSingleton;
}
# if 0
//推荐不要增加这个功能,因为是单例模式如果释放了
//就没了,全局就这一个变量。
static void freeSpace()
{
if(pSingleton != NULL)
{
delete pSingleton;
}
}
# endif
//嵌套类
class Garbo
{
public:
Garbo()
{
cout << "Garbo()" << endl;
}
~Garbo()
{
cout << "~Garbo" << endl;
if(pSingleton != NULL)
{

delete pSingleton;
}
}

};
private:
static Singleton_hungry* pSingleton;
static Garbo  garbo;
};
//类外初始化
Singleton_hungry* Singleton_hungry::pSingleton = new Singleton_hungry;
//注意要这样写
Singleton_hungry::Garbo Singleton_hungry::garbo = Garbo();




void test01()
{
Singleton_lazy* p1 = Singleton_lazy::getInstance();
Singleton_lazy* p2 = Singleton_lazy::getInstance();
if(p1 == p2)
{
cout << "俩个指针指向同一快内存空间,是单例" << endl;
}
else
{
cout << "不是单例模式" << endl;
}


Singleton_hungry* p3 = Singleton_hungry::getInstance();
Singleton_hungry* p4 = Singleton_hungry::getInstance();
if(p3 == p4)
{
cout << "俩个指针指向同一快内存空间,是单例" << endl;
}
else
{
cout << "不是单例模式" << endl;
}



}






//单例对象释放问题
void test02()
{
// Singleton_hungry::freeSpace();
}


int main(int argc, char *argv[])
{
cout << "main函数开始执行" << endl;
test01();


return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值