#include <iostream>
using namespace std;
class MyInstance
{
MyInstance(){}
public:
static MyInstance *getInstance()
{
if(m_instance == NULL)
{
m_instance = new MyInstance();
cout << "getInstance " << m_instance << endl;
static Release r;
}
return m_instance;
}
/* 用于释放对象 */
class Release
{
public:
~Release()
{
if(MyInstance::m_instance != NULL)
{
cout << "~Release" << endl;
delete MyInstance::m_instance;
MyInstance::m_instance = NULL;
}
}
};
private:
static MyInstance *m_instance;
};
MyInstance *MyInstance::m_instance = NULL;
int main()
{
MyInstance *m_instance1 = MyInstance::getInstance();
cout << "m_instance1 " << m_instance1 << endl;
MyInstance *m_instance2 = MyInstance::getInstance();
cout << "m_instance2 " << m_instance2 << endl;
return 0;
}
$ ./a.out
getInstance 0x121fc20
m_instance1 0x121fc20
m_instance2 0x121fc20
~Release