/* * singleton.cpp * * Singleton example. Ensure a class has only one instance * and provide a global point of access. */ #include class Singleton { public: static Singleton* instance() { if (_instance == 0) _instance = new Singleton(); return _instance; } ~Singleton() { if (_instance != 0) delete _instance; } void operation() { std::cout << "Singleton " << this << "\n"; } protected: Singleton() {}; private: static Singleton* _instance; }; // Static variable definition would be in the .cpp file. Singleton* Singleton::_instance = 0; int main() { Singleton* s1 = Singleton::instance(); s1->operation(); Singleton* s2 = Singleton::instance(); s2->operation(); }