日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

std string与线程安全_这才是现代C++单例模式简单又安全的实现

發布時間:2025/4/16 c/c++ 98 豆豆
生活随笔 收集整理的這篇文章主要介紹了 std string与线程安全_这才是现代C++单例模式简单又安全的实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

說到單例模式,很多人可能都已經很熟悉了,這也是面試常問的一個問題。對于單線程而言,單例的實現非常簡單,而要寫出一個線程安全的單例模式,曾經有很多種寫法。有興趣的可以參考這篇文章《單例模式很簡單?但是你真的能寫對嗎?》

簡單實現

該文章中也提到,由于C++11及以后的版本中,默認靜態變量初始化是線程安全的。

The initialization of such a variable is defined to occur the first time control passes through its declaration; for multiple threads calling the function, this means there’s the potential for a race condition to define first.

寫法如下:

//來源:公眾號編程珠璣
//作者:守望先生
class?Singleton{
public:
????static?Singleton&?getInstance(){
????????static?Singleton?m_instance;??//局部靜態變量
????????return?m_instance;
????}
????Singleton(const?Singleton&?other)?=?delete;
????Singleton&?operator=(const?Singleton&?other)?=?delete;
protected:
????Singleton()?=?default;
????~Singleton()?=?default;
};

這里需要注意將其他構造函數設置為delete。避免對象被再次構造或者拷貝。

這種單例被稱為Meyers' Singleton。

通用化

當然為了避免給每個對象都單獨寫個單例,也可以利用模板。

template<typename?T>
class?Singleton
{
public:
????static?T&?getInstance()?{
????????static?T?t;
????????return?t;
????}

????Singleton(const?Singleton&)?=?delete;?
????Singleton&?operator=(const?Singleton&)?=?delete;?
protected:
????Singleton()?=?default;
????~Singleton()?=?default;
};

示例

舉個簡單的例子來看下吧:

//來源:公眾號編程珠璣
//作者:守望先生
#include
template<typename?T>
class?Singleton
{
public:
????static?T&?getInstance()?{
????????static?T?t;
????????return?t;
????}

????Singleton(const?Singleton&)?=?delete;?
????Singleton&?operator=(const?Singleton&)?=?delete;?
protected:
????Singleton()?=?default;
????~Singleton()?=?default;
};
class?Test:public?Singleton
{public:void?myprint(){std::cout<<"test?Singleton"<<std::endl;
????}
};int?main(){
????Test::getInstance().myprint();return?0;
}

編譯運行:

$?g++?-o?test?test.cc?-std=c++11
$?./test
test?Singleton

另一種用法

當然你也可以像下面這樣使用:

class?Test
{
public:
????void?myprint(){
????????std::cout<<"test?Singleton"<<std::endl;
????}
};
int?main(){
????Singleton::getInstance().myprint();return?0;
}

轉載自網絡

總結

以上是生活随笔為你收集整理的std string与线程安全_这才是现代C++单例模式简单又安全的实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。