何時/如何使用 std::enable_shared_from_this<T>?

来源:https://www.cnblogs.com/Steven-HU/p/18252632
-Advertisement-
Play Games

最近項目中使用了PowerJob做任務調度模塊,感覺這個框架真香,今天我們就來深入瞭解一下新一代的定時任務框架——PowerJob! 簡介 PowerJob是基於java開發的企業級的分散式任務調度平臺,與xxl-job一樣,基於web頁面實現任務調度配置與記錄,使用簡單,上手快速,其主要功能特性如 ...


要點回顧


  • 繼承自 std::enable_shared_from_this<T> 的類能夠在其自身實例中通過 std::shared_from_this 方法創建一個指向自己的 std::shared_ptr<T> 智能指針。
  • 從一個裸指針創建多個 std::shared_ptr<T> 實例會造成嚴重的後果,其行為是未定義的。
  • std::enable_shared_from_this<T> 實際包含了一個用於指向對象自身的 std::weak_ptr<T> 指針。

引言


本文介紹 std::enable_shared_from_thisstd::shared_from_this 的基本概念和使用方法。

定義 "std::enable_shared_from_this"


以下內容是 cppreference.com 上關於 std::enable_shared_from_this 的定義和說明:

Defined in header < memory >
template< class T > class enable_shared_from_this; (since C++11)

std::enable_shared_from_this allows an object t that is currently managed by a std::shared_ptr named pt to safely generate additional std::shared_ptr instances pt1, pt2, ... that all share ownership of t with pt.

Publicly inheriting from std::enable_shared_from_this<T> provides the type T with a member function shared_from_this. If an object t of type T is managed by a std::shared_ptr<T> named pt, then calling T::shared_from_this will return a new std::shared_ptr<T> that shares ownership of t with pt.

簡單來說就是,繼承自 std::enable_shared_from_this<T> 的類能夠在其自身實例中通過 std::shared_from_this 方法創建一個指向自己的 std::shared_ptr<T> 智能指針。

想要理解 std::enable_shared_from_this<T>,首先得知道為什麼需要 std::enable_shared_from_this<T>,請看下文。


使用 "std::enable_shared_from_this"


為什麼需要 std::enable_shared_from_this<T>? 我們從一個例子講起,會更容易一些。

假定有一個類 Processor, 它的作用是非同步處理數據並且存儲到資料庫。當 Processor 接收到數據時,它通過一個定製的 Executor 類型來非同步處理數據:

class Executor {
public:
 //Executes a task asynchronously
 void
 execute(const std::function<void(void)>& task);
 //....
private:
 /* Contains threads and a task queue */
};

class Processor {
public:
 //...
 //Processes data asynchronously. (implemented later)
 void processData(const std::string& data); 

private:
 //Called in an Executor thread 
 void doProcessAndSave(const std::string& data) {
    //1. Process data
    //2. Save data to DB
 }
 //.. more fields including a DB handle..
 Executor* executor;
};

Client 類包含了一個 std::shared_ptr<Processor> 實例,Processor 從 Client 類接收數據:

class Client {
public:
 void someMethod() {
  //...
  processor->processData("Some Data");
  //..do something else
 }
private:
 std::shared_ptr<Processor> processor;
};

以上示例中,Executor 是一個線程池,用於執行任務隊列中的任務。
Processor::processData 中,我們需要傳遞一個(指針)函數(lambda 函數)給 Executor 來執行非同步操作。該 lambda 函數調用 Processor::doProcessAndSave 以完成實際的數據處理工作。因此,該 lambda 函數需要捕獲一個 Processor 對象的引用/指針。我們可以這樣做:

void Processor::processData(const std::string& data) {
 executor->execute([this, data]() { //<--Bad Idea
   //Executes in an Executor thread asynchronously
   //'this' could be invalid here.
   doProcessAndSave(data);
 });
}

然而,因為種種原因,Client 可能會隨時重置 std::shared_ptr<Processor>,這可能導致 Processor 的實例被析構。因此,在執行 execute 函數時或者在執行之前,上述代碼中捕獲的 this 指針隨時可能會變為無效指針。

怎麼辦?

我們可以通過在 lambda 函數中捕獲並保留一個指向當前對象本身的 std::shared_ptr<Processor> 實例來防止 Processor 對象被析構。

下圖展示了示例代碼的交互邏輯:

那麼,在 Processor 實例中通過 shared_ptr(this) 創建一個智能指針呢?其行為是未定義的!

std::shared_ptr<T> 允許我們安全地訪問和管理對象的生命周期。多個 std::shared_ptr<T> 實例通過一個共用控制塊結構(a shared control block structure)來管理對象的生命周期。一個控制塊維護了一個引用計數,及其他必要的對象本身的信息。

void good() {
 auto p{new int(10)}; //p is int*
 std::shared_ptr<int> sp1{p}; 
 //Create additional shared_ptr from an existing shared_ptr
 auto sp2{sp1}; //OK. sp2 shares control block with sp1
}

從一個裸指針創建一個 std::shared_ptr<T> 會創建一個新的控制塊。從一個裸指針創建多個 std::shared_ptr<T> 實例會造成嚴重的後果:

void bad() {
 auto p{new int(10)};   
 std::shared_ptr<int> sp1{p};
 std::shared_ptr<int> sp2{p}; //! Undefined Behavior
}

因此,我們需要一個機制能夠達到我們的目的(捕獲並保留一個指向當前對象本身的 std::shared_ptr<Processor> 實例)。

這就是 std::enable_shared_from_this<T> 存在的意義,以下是修改後的類 Processor 實現:

class Processor : public std::enable_shared_from_this<Processor> {
 //..same as above...
}; 

void Processor::processData(const std::string& data) {
 //shared_from_this() returns a shared_ptr<Processor> 
 //  to this Processor
 executor->execute([self = shared_from_this(), data]() { 
   //Executes in an Executor thread asynchronously
   //'self' is captured shared_ptr<Processor>
   self->doProcessAndSave(data); //OK. 
 });
}

self = shared_from_this() 傳遞的是一個合法的 std::shared_ptr<Processor> 實例,合法的類 Processor 對象的引用。


深入 "std::enable_shared_from_this" 內部


std::enable_shared_from_this<T> 的實現類似:

template<class T>
class enable_shared_from_this {
 mutable weak_ptr<T> weak_this;
public:
 shared_ptr<T> shared_from_this() {
  return shared_ptr<T>(weak_this); 
 }
 //const overload
 shared_ptr<const T> shared_from_this() const {
  return shared_ptr<const T>(weak_this); 
 }

 //..more methods and constructors..
 //there is weak_from_this() also since C++17

 template <class U> friend class shared_ptr;
};

enable_shared_from_this 包含了一個 std::weak_ptr<T> 指針,這正是函數 shared_from_this 返回的內容。註意,為什麼不是 std::shared_ptr<T>? 因為對象包含自身的計數引用會導致對象永遠不被釋放,從而發生記憶體泄漏。上述代碼中 weak_this 會在類對象被 std::shared_ptr<T> 引用時賦值,也就是std::shared_ptr<T> 實例的構造函數中賦值,這也是為什麼類 enable_shared_from_this 的最後,其被聲明成為了 shared_ptr 的友元。


總結


到此,關於 std::enable_shared_from_this<T> 的介紹就結束了。


引用


https://en.cppreference.com/w/cpp/memory/enable_shared_from_this
https://www.nextptr.com/tutorial/ta1414193955/enable_shared_from_this-overview-examples-and-internals


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Windows應用軟體開發,會有很多常用的模塊,比如資料庫、配置文件、日誌、後臺通信、進程通信、埋點、瀏覽器等等。下麵是目前我們公司windows梳理的部分組件,梳理出來方便大家瞭解組件概念以及依賴關係: 每個應用里,現在或者以後都可能會存在這些模塊。以我團隊開發的全家桶為例,十多個應用對後臺訪問, ...
  • 通過本文我們深入瞭解了RabbitMQ的集群模式及其優缺點。無論是普通集群還是鏡像集群,都有其適用的場景和局限性。普通集群利用Erlang語言的集群能力,但消息可靠性和高可用性方面存在一定挑戰;而鏡像集群通過主動消息同步提高了消息的可靠性和高可用性,但可能會占用大量網路帶寬。因此,在選擇集群方案時,... ...
  • 寫在前面 在現目前項目開發中,一般都是前後端分離項目。前端小姐姐負責開發前端,苦逼的我們負責後端開發 事實是一個人全乾,在這過程中編寫介面文檔就顯得尤為重要了。然而作為一個程式員,最怕的莫過於自己寫文檔和別人不寫文檔 大家都不想寫文檔,那這活就交給今天的主角Swagger來實現了 一、專業名詞介紹 ...
  • 1 Zero-shot learning 零樣本學習。 1.1 任務定義 利用訓練集數據訓練模型,使得模型能夠對測試集的對象進行分類,但是訓練集類別和測試集類別之間沒有交集;期間需要藉助類別的描述,來建立訓練集和測試集之間的聯繫,從而使得模型有效。 Zero-shot learning 就是希望我們 ...
  • 本文基於 OpenJDK17 進行討論,垃圾回收器為 ZGC。 提示: 為了方便大家索引,特將在上篇文章 《以 ZGC 為例,談一談 JVM 是如何實現 Reference 語義的》 中討論的眾多主題獨立出來。 FinalReference 對於我們來說是一種比較陌生的 Reference 類型,因 ...
  • 目錄智能指針場景引入 - 為什麼需要智能指針?記憶體泄漏什麼是記憶體泄漏記憶體泄漏的危害記憶體泄漏分類如何避免記憶體泄漏智能指針的使用及原理RAII簡易常式智能指針的原理智能指針的拷貝問題智能指針的發展歷史std::auto_ptr模擬實現auto_ptr常式:這種方案存在的問題:Boost庫中的智能指針un ...
  • NumPy 助你處理數學問題:計算序列的差分用`np.diff()`,示例返回`[5, 10, -20]`;找最小公倍數(LCM)用`np.lcm()`,數組示例返回`18`;最大公約數(GCD)用`np.gcd.reduce()`,數組示例返回`4`;三角函數如`np.sin()`,`np.deg... ...
  • 本框架JSON元素組成和分析,JsonElement分三大類型JsonArray,JsonObject,JsonString。 JsonArray:數組和Collection子類,指定數組的話,使用ArrayList來add元素,遍歷ArrayList再使用Array.newInstance生成數組 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...