单例模式以及垃圾回收
#include <iostream>#include <mutex>using namespace std;mutex *m_mutex;class Sington{private:Sington(){cout << "Sington()" << endl;stat
·
#include <iostream>
#include <mutex>
using namespace std;
mutex *m_mutex;
class Sington
{
private:
Sington()
{
cout << "Sington()" << endl;
static GarbageCollection g;
}
public:
static Sington* p;
static Sington* getinstance()
{
if(p == NULL)
{
m_mutex->lock();
if(p == NULL)
{
p = new Sington();
}
m_mutex->unlock();
}
return p;
}
~Sington() { cout << "~Sington()" << endl; }
class GarbageCollection
{
public:
~GarbageCollection()
{
if(Sington::p != NULL)
{
cout << hex << "delete p at " << p << endl;
delete Sington::p;
Sington::p = NULL;
}
}
};
};
Sington* Sington::p = NULL;
int main()
{
Sington* sgt1 = Sington::getinstance();
Sington* sgt2 = Sington::getinstance();
cout << hex << "sgt1=" << sgt1 << " sgt2=" << sgt2 << endl;
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)