cpp Singleton pattern
class Singleton { public: static Singleton* getInstance(){ if (m_sInstance == 0) { m_sInstance = new Singleton(); } return m_sInstance; } static void releaseInstance(){ if(nullptr != m_sInstance) { delete m_sInstance; m_sInstance = nullptr; } }
/* more (non-static) functions here */
private: Singleton(); // ctor hidden Singleton(Singleton const&); // copy ctor hidden Singleton& operator=(Singleton const&){ return *m_sInstance; }; // assign op. hidden ~Singleton(); // dtor hidden
static Singleton* m_sInstance; };
/* Null, because instance will be initialized on demand. */ Singleton* Singleton::m_sInstance = 0;
Singleton* Singleton::getInstance() { if (m_sInstance == 0) { m_sInstance = new Singleton(); } return m_sInstance; }
Singleton::Singleton() {}
int main() { //new Singleton(); // Won't work Singleton* s = Singleton::getInstance(); // Ok Singleton* r = Singleton::getInstance();
/* The addresses will be the same. */ std::cout << s << std::endl; std::cout << r << std::endl; }
|