C++11线程安全的单例模式
生活随笔
收集整理的這篇文章主要介紹了
C++11线程安全的单例模式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
單例模式
C++11規(guī)定了local static在多線程條件下的初始化行為,要求編譯器保證了內(nèi)部靜態(tài)變量的線程安全性。在C++11標(biāo)準(zhǔn)下,《Effective C++》提出了一種更優(yōu)雅的單例模式實(shí)現(xiàn),使用函數(shù)內(nèi)的 local static 對(duì)象。這樣,只有當(dāng)?shù)谝淮卧L問getInstance()方法時(shí)才創(chuàng)建實(shí)例。這種方法也被稱為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總結(jié)
以上是生活随笔為你收集整理的C++11线程安全的单例模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机网络各层协议
- 下一篇: QT 中textEdit 和 textB