首页 > 编程语言 > 详细

C++ 单例模式实现

时间:2017-07-15 10:53:47      阅读:254      评论:0      收藏:0      [点我收藏+]
 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 }

 

C++ 单例模式实现

原文:http://www.cnblogs.com/wxquare/p/4730499.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!