1 #include <iostream> 2 using namespace std; 3 4 /************************************************************************/ 5 /*Lazy Singletom(非线程安全) */ 6 /************************************************************************/ 7 class singleton 8 { 9 public: 10 static singleton& Instance() 11 { 12 if (ps == NULL) 13 { 14 ps = new singleton; 15 } 16 return *ps; 17 } 18 private: 19 singleton(); 20 singleton(const singleton&); 21 ~singleton(); 22 static singleton* ps; 23 }; 24 singleton*singleton::ps = NULL; 25 26 /************************************************************************/ 27 /* Eager singleton(线程安全) */ 28 /* 函数外的staic对象在不同编译单元初始化顺序不固定,两个线程交互会产生问题*/ 29 /************************************************************************/ 30 class singleton 31 { 32 public: 33 static singleton& Instance() 34 { 35 return instance; 36 } 37 private: 38 singleton(); 39 singleton(const singleton&); 40 ~singleton(); 41 static singleton instance; 42 }; 43 singleton singleton::instance; 44 45 /************************************************************************/ 46 /* Meyes singleton C++11后为线程安全 */ 47 /************************************************************************/ 48 class singleton 49 { 50 public: 51 static singleton& Instance() 52 { 53 return static singleton instance; 54 } 55 private: 56 singleton(); 57 singleton(const singleton&); 58 ~singleton(); 59 }; 60 61 /************************************************************************/ 62 /* Double_lock 基于线程安全的懒加载 */ 63 /************************************************************************/ 64 class singleton 65 { 66 public: 67 static singleton& Instance() 68 { 69 if (ps == NULL) 70 { 71 lock(); 72 if (ps == NULL) 73 { 74 ps = new singleton; 75 } 76 unlock(); 77 } 78 return *ps; 79 } 80 private: 81 singleton(); 82 ~singleton(); 83 singleton(const singleton&); 84 static singleton* ps; 85 }; 86 singleton* singleton::ps = NULL;