C++ 单例模式实现

 1 #include <iostream>
 2 #include <mutex>
 3 
 4 std::mutex mtx;
 5 class Singleton {
 6 private:
 7     Singleton() {}
 8     Singleton(const Singleton& a);
 9     Singleton& operator=(const Singleton&);
10     static Singleton * instance;
11 public:
12     static Singleton* getInstance() {
13         if (instance == nullptr) {
14             mtx.lock();
15             if((instance == nullptr)){
16                 instance =  new Singleton();
17             }
18             mtx.unlock();
19         }
20         return instance;
21     }
22 };
23 Singleton* Singleton::instance = nullptr;
24 
25 int main(){
26     Singleton* instance1 = Singleton::getInstance();
27     Singleton* instance2 = Singleton::getInstance();
28     if(instance1 == instance2){
29         std::cout << "singleton" << std::endl;
30     }
31     return 0;
32 }

 

posted @ 2017-08-06 17:24  wxquare  阅读(329)  评论(0编辑  收藏  举报