如果存在实例,直接返回,不存在就创建,关键点是别忘了静态变量的初始化。
#include <iostream>
using namespace std;
class Singleton
{
private:
Singleton()
{
}
static Singleton* m_pInstance;
public:
static Singleton* getInstance()
{
if( NULL == m_pInstance )
return new Singleton();
else
return m_pInstance;
}
void display()
{
cout << "hello world" << endl;
}
};
Singleton* Singleton::m_pInstance = NULL;
int main()
{
Singleton *obj;
obj = Singleton::getInstance();
obj->display();
return 0;
}