将对象建立在堆区
上文阐述的是将对象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()函数地隐式调用,这种方法将在后文中给出。