64,646
社区成员
发帖
与我相关
我的任务
分享
class Singleton
{
private:
static Singleton * instance;
//引用计数
static int count;
Singleton()
{
count++;
}
public:
static Singleton* GetInstance()
{
if(count == 0)
instance = new Singleton();
return instance;
}
~Singleton()
{
cout <<"Singleton is deleted!" <<endl;
}
void Display()
{
cout <<"Singleton!" <<endl;
}
void Destroy()
{
count--;
if(count == 0)
delete instance;
}
};
int Singleton::count = 0;
Singleton * Singleton::instance = NULL;
void main()
{
Singleton* pInstance = Singleton::GetInstance();
pInstance->Display();
pInstance->Destroy();
_CrtDumpMemoryLeaks();
}
~Singleton()
{
if(instance != NULL)
{
delete instance;
instance = NULL;
}
}
- -b
你这个是干嘛呢,无限调用了。。。。
#include <iostream>
#include <crtdbg.h>
using namespace std;
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();
}
完全没有问题啊,编译和运行都没有问题: