1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
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; }
|
近期评论