单件模式释放空间
在实现单件模式时,由于一般不会释放单件空间,往往都会造成内存的泄漏
我想了一个方法,就是使用一个类GC,在Singleton中声明一个GC的静态对象将单件的空间释放!!
但是还有点错误!!
请大虾看一下哪里有错??
或者提供一种好的释放单件内存的方法!!
谢谢!!!
#include<iostream.h>
#include<crtdbg.h>
class GC
{
public:
GC();
~GC();
protected:
private:
};//垃圾回收类
class Singleton
{
public:
friend class GC;
static Singleton* GetInstance()
{
if(instance == NULL)
{
static GC gc;
instance = new Singleton;
}
return instance;
}
~Singleton()
{
if(instance != NULL)
{
delete instance;
instance = NULL;
}
}
void Display()
{
cout<<"Singleton!"<<endl;
}
protected:
Singleton(){}
Singleton(const Singleton& other){}
Singleton& operator=(const Singleton& other){}
private:
static Singleton* instance;
};
Singleton* Singleton::instance = NULL;
GC::GC()
{
cout<<"Con GC!"<<endl;
}
GC::~GC()
{
Singleton* pInstance = Singleton::GetInstance();
if (pInstance != NULL)
{//回收空间
delete pInstance;
pInstance = NULL;
cout<<"Delete Singleton::instance in GC!"<<endl;
}
}
void main()
{
Singleton* pInstance = Singleton::GetInstance();
pInstance->Display();
_CrtDumpMemoryLeaks();
}
我想了一个方法,就是使用一个类GC,在Singleton中声明一个GC的静态对象将单件的空间释放!!
但是还有点错误!!
请大虾看一下哪里有错??
或者提供一种好的释放单件内存的方法!!
谢谢!!!
#include<iostream.h>
#include<crtdbg.h>
class GC
{
public:
GC();
~GC();
protected:
private:
};//垃圾回收类
class Singleton
{
public:
friend class GC;
static Singleton* GetInstance()
{
if(instance == NULL)
{
static GC gc;
instance = new Singleton;
}
return instance;
}
~Singleton()
{
if(instance != NULL)
{
delete instance;
instance = NULL;
}
}
void Display()
{
cout<<"Singleton!"<<endl;
}
protected:
Singleton(){}
Singleton(const Singleton& other){}
Singleton& operator=(const Singleton& other){}
private:
static Singleton* instance;
};
Singleton* Singleton::instance = NULL;
GC::GC()
{
cout<<"Con GC!"<<endl;
}
GC::~GC()
{
Singleton* pInstance = Singleton::GetInstance();
if (pInstance != NULL)
{//回收空间
delete pInstance;
pInstance = NULL;
cout<<"Delete Singleton::instance in GC!"<<endl;
}
}
void main()
{
Singleton* pInstance = Singleton::GetInstance();
pInstance->Display();
_CrtDumpMemoryLeaks();
}
...全文
相关推荐
设计模式 单件模式 设计模式 单件模式
单件模式单件模式单件模式单件模式单件模式单件模式单件模式单件模式
oracle定时删除表空间的数据并释放表空间
oracle定时删除表空间的数据并释放表空间
Linux如何处理文件已删除但空间不释放的问题
主要介绍了Linux如何处理文件已删除但空间不释放的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
c++实现单件模式 c++实现单件模式 c++实现单件模式
参考多个资料,自己写的一个单件模式 参考多个资料,自己写的一个单件模式 参考多个资料,自己写的一个单件模式
设计模式 之 单件模式
架构和模式应该是一个属于相互涵盖的过程,但是总体来说架构更加关注的是所谓的High-Level Design,而模式关注的重点在于通过经验提取的“准则或指导方案”在设计中的应用,因此在不同层面考虑问题的时候就形成了不同问题域上的模式。模式的目标是,把共通问题中的不变部分和变化部分分离出来。不变的部分,就构成了模式,因此,模式是一个经验提取的“准则”,并且在一次一次的实践中得到验证,在不同的层次有不同的模式,小到语言实现,大到架构。在不同的层面上,模式提供不同层面的指导。


