对单例设计模式的学习(二)--饿汉式:将对象建立在堆区的单例模式

将对象建立在堆区

上文阐述的是将对象Instance建立在静态区的情况,这种对象会伴随着程序共同消亡,所以析构函数能够被调用到;同样的也将带来弊端,程序可能受内存限制,静态区的空间不足,且对象无法手动进行释放,所以就有了将对象建立在堆区new出来的形式。

class CSingleton
{
public:
	static CSingleton *GetInstance();
	static void DelInstance();
private:
	CSingleton();
	~CSingleton();
	CSingleton(const CSingleton &instance);
	CSingleton & operator=(const CSingleton &instance);
	static CSingleton *Instance;
};

可以观察到 类中已经改成一个静态的指向对象的指针。且多了一个函数static void DelInstance();
这个函数的作用是手动的释放对象,因为析构函数被私有化,不能直接delete对象(编译会报错)。

#include "Singleton.h"
#include<iostream>
using namespace std;

CSingleton * CSingleton::GetInstance()
{
	if (!Instance)
	{
		Instance = new CSingleton;
	}
	return Instance;
}

void CSingleton::DelInstance()
{
	if(Instance)
	delete Instance;
}

CSingleton::CSingleton()
{
	Instance = NULL;
	cout << "构造 ";
}


CSingleton::~CSingleton()
{
	Instance = NULL;
	cout << "析构";
	system("pause");
}

附上测试代码

#include<iostream>
#include"Singleton.h"
using namespace std;
CSingleton* CSingleton::Instance = new CSingleton;
int main()
{
	CSingleton *instance = CSingleton::GetInstance();
	CSingleton *instance2 = CSingleton::GetInstance();
	CSingleton::DelInstance();
	return 0;
}

附上测试结果
在这里插入图片描述
可知,构造与析构均被正常调用到,不会产生内存泄漏的问题。

如何解决需要显式地调用DelInstance();函数的问题?

这里存在两种解决方式,其一是在CSingleton中定义一个内部类,如图

class CSingleton
{
public:
	static CSingleton *GetInstance();
	static void DelInstance();
private:
	CSingleton();
	~CSingleton();
	CSingleton(const CSingleton &instance);
	CSingleton & operator=(const CSingleton &instance);
	static CSingleton *Instance;
private:
	class MyClass
	{
	public:
		MyClass() {};
		~MyClass() 
		{
			if (Instance)
				delete Instance;
		};
	};
	static MyClass sign;
};

附上测试代码

#include<iostream>
#include"Singleton.h"
using namespace std;
CSingleton* CSingleton::Instance = new CSingleton;
CSingleton::MyClass CSingleton::sign;
int main()
{
	CSingleton *instance = CSingleton::GetInstance();
	CSingleton *instance2 = CSingleton::GetInstance();
	//CSingleton::DelInstance();
	return 0;
}

在这里插入图片描述
测试结果成功,由此,梳理下过程,定义的sign变量存在静态区中,当程序消亡时,sign变量的析构函数被调用到,析构函数中调用了delete Instance。所以CSingleton的析构函数也被成功调用到,这样就 巧妙地隐去了DelInstance()函数;即可手动也可自动释放这个堆区变量。
另一种方式是使用智能指针来实现DelInstance()函数地隐式调用,这种方法将在后文中给出。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值