1 // from the header file 2 class Singleton { 3 public: 4 static Singleton* instance(); 5 ... 6 private: 7 static Singleton* pInstance; 8 }; 9 10 // from the implementation file 11 Singleton* Singleton::pInstance = 0; 12 13 Singleton* Singleton::instance() { 14 if (pInstance == 0) { 15 pInstance = new Singleton; 16 } 17 return pInstance; 18 }
Example 1: In single-threaded environments, this code generally works okay.