00001 // From 00002 // http://en.wikipedia.org/wiki/Singleton_pattern 00003 00004 #include <iostream> 00005 using namespace std; 00006 00007 /* Place holder for thread synchronization mutex */ 00008 class Mutex 00009 { /* placeholder for code to create, use, and free a mutex */ 00010 }; 00011 00012 /* Place holder for thread synchronization lock */ 00013 class Lock 00014 { public: 00015 Lock(Mutex& m) : mutex(m) { /* placeholder code to acquire the mutex */ } 00016 ~Lock() { /* placeholder code to release the mutex */ } 00017 private: 00018 Mutex & mutex; 00019 }; 00020 00021 class Singleton 00022 { public: 00023 static Singleton* GetInstance(); 00024 int a; 00025 ~Singleton() { cout << "In Dtor" << endl; } 00026 00027 private: 00028 Singleton(int _a) : a(_a) { cout << "In Ctor" << endl; } 00029 00030 00031 static Mutex mutex; 00032 00033 // Not defined, to prevent copying 00034 Singleton(const Singleton& ); 00035 Singleton& operator =(const Singleton& other); 00036 }; 00037 00038 Mutex Singleton::mutex; 00039 00040 Singleton* Singleton::GetInstance() 00041 { 00042 Lock lock(mutex); 00043 00044 cout << "Get Inst" << endl; 00045 00046 // Initialized during first access 00047 static Singleton inst(1); 00048 00049 return &inst; 00050 } 00051 00052 int main() 00053 { 00054 Singleton* singleton = Singleton::GetInstance(); 00055 cout << "The value of the singleton: " << singleton->a << endl; 00056 return 0; 00057 } 00058 00059 /*Output: 00060 Get Inst 00061 In Ctor 00062 The value of the singleton: 1 00063 In Dtor 00064 */