C++11线程安全的单例模式
生活随笔
收集整理的這篇文章主要介紹了
C++11线程安全的单例模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
單例模式
C++11規定了local static在多線程條件下的初始化行為,要求編譯器保證了內部靜態變量的線程安全性。在C++11標準下,《Effective C++》提出了一種更優雅的單例模式實現,使用函數內的 local static 對象。這樣,只有當第一次訪問getInstance()方法時才創建實例。這種方法也被稱為Meyers’ Singleton。
class Singleton { private:Singleton() { };~Singleton() { };Singleton(const Singleton&);Singleton& operator=(const Singleton&); public:static Singleton& getInstance() {static Singleton instance;return instance;} };例子
#include <iostream>class SigleInstance{ public: static SigleInstance& GetInstance(){static SigleInstance instance;return instance; } void fun(){std::cout << ++num << std::endl; } private: int num; SigleInstance():num(0){} ~SigleInstance(){} };int main(){for(int i = 0; i < 10; ++i){SigleInstance::GetInstance().fun();}return 0; } # result 1 2 3 4 5 6 7 8 9 10總結
以上是生活随笔為你收集整理的C++11线程安全的单例模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机网络各层协议
- 下一篇: 基于Hadoop的hbase安装