#include using namespace std; class Singleton { public: static Singleton* InstancePointer(); static Singleton& InstanceReference(); void Show(); void Increment(); private: Singleton(); static Singleton* m_Instance; // other data members int m_x; }; //must initialize static members outside of class definition Singleton* Singleton::m_Instance = NULL; Singleton::Singleton() { m_x = 0; } Singleton* Singleton::InstancePointer() { if (m_Instance == NULL) { m_Instance = new Singleton; } return m_Instance; } Singleton& Singleton::InstanceReference() { if (m_Instance == NULL) { m_Instance = new Singleton; } return *m_Instance; } void Singleton::Show() { cout << "Singleton m_x = " << m_x << endl; } void Singleton::Increment() { m_x++; } void main() { Singleton* s1 = Singleton::InstancePointer(); Singleton* s2 = Singleton::InstancePointer(); Singleton& s3 = Singleton::InstanceReference(); s1->Show(); s2->Show(); s3.Show(); s1->Increment(); s2->Show(); s3.Show(); Singleton::InstanceReference().Increment(); Singleton::InstanceReference().Show(); s1->Show(); //which is safer returing a reference or pointer //delete s2; }