class MySingleton { private: MySingleton(){} static MySingleton *m_pInstance; public: static MySingleton* GetInstance() { if(!m_pInstance) m_pInstance = new MySingleton(); return m_pInstance; } void sayHello() { std::cout << "Hello world" << std::endl; } }; MySingleton* MySingleton::m_pInstance = NULL;
注:必须对类中的静态变量m_pInstance进行初始化,否则编译报如下错误
/tmp/ccSDAtaL.o: In function `MySingleton::GetInstance()': singleton.cpp:(.text._ZN11MySingleton11GetInstanceEv[MySingleton::GetInstance()]+0x8): undefined reference to `MySingleton::m_pInstance' singleton.cpp:(.text._ZN11MySingleton11GetInstanceEv[MySingleton::GetInstance()]+0x28): undefined reference to `MySingleton::m_pInstance' singleton.cpp:(.text._ZN11MySingleton11GetInstanceEv[MySingleton::GetInstance()]+0x2d): undefined reference to `MySingleton::m_pInstance' collect2: ld return 1
class MySingleton { private: MySingleton(){} static MySingleton *m_pInstance; class CGarbo //在析构函数中删除MySingleton单体实例 { public: CGarbo() { std::cout << "CGarbo() is called" << std::endl; } ~CGarbo() { std::cout << "~CGarbo() is called" << std::endl; if (MySingleton::m_pInstance) delete MySingleton::m_pInstance; } }; static CGarbo Garbo; //声明为私有静态成员 public: static MySingleton* GetInstance() { if(!m_pInstance) m_pInstance = new MySingleton(); return m_pInstance; } void sayHello() { std::cout << "Hello world" << std::endl; } }; MySingleton* MySingleton::m_pInstance = NULL; MySingleton::CGarbo MySingleton::Garbo;注:必须在类外对Garbo进行初始化,否则由于Garbo没有实例化,所以不会调用析构函数释放MySingleton单体实例。