smart pointer --- shared_from_this的使用


shared_ptr     enable_shared_from_this

一種避免內存泄漏的方式是, always use a named smart pointer variable to hold the result of new

shared_ptr<T>  p(new T);

http://hi.baidu.com/jrckkyy/blog/item/ac3e5511fa4a59caa6ef3ff1.html    這篇文章講了shared_from_this幾個值得注意的地方, 看了幾次,然后去翻閱了下源碼,搞明白了

boost文檔中首先講了enable_shared_from_this的作用 : The header <boost/enable_shared_from_this.hpp> defines the class template enable_shared_from_this. It is used as a base class that allows a shared_ptr to the current object to be obtained from within a member function.

1. enable_shared_from_this<D> 作為D的基類, 這樣D就繼承了它的兩個public函數,  shared_ptr<D> shared_from_this() ;  const shared_ptr<D>  shared_from_this  const ();

2. D對象本身是不可以直接調用 shared_from_this()的, 在boost的代碼設計中, D繼承自 enable_shared_from_this<D> 的 private成員  weak_ptr<D> weak_this_  是從第三方函數調用D._internal_accept_owner(shared_ptr<D> const * Dptr,  D * pD)  來初始化, 而這個第三方函數是在 shared_ptr.hpp中實現的, 且由 shared_ptr<>的構造函數調用(很容易的把this傳過去)

以下代碼例子

 1 #include <boost/shared_ptr.hpp>
2 #include <boost/enable_shared_from_this.hpp>
3 #include <iostream>
4
5 using namespace std;
6 using namespace boost;
7
8 class WY : public enable_shared_from_this<WY>{
9 public:
10 WY (int i):i_(i) { cout << "WY's constructor" << endl; }
11
12 int i (){return i_;}
13
14 shared_ptr<WY> get_shared_ptr (){
15 cout << "in get_shared_ptr ==> i = " << i_ << endl;
16 return shared_from_this();
17 }
18 private :
19 int i_;
20 };
21
22 int main ()
23 {
24 WY wy(6); //這個wy對象實際上它的成員(繼承自enable_shared_from_this<WY>) weak_ptr<WY>, 並有被初始化, 所以調用wy.shared_from_this()會拋錯
25 shared_ptr<WY> ptr(new WY(5)); //這個ptr所持有的WY, 其weak_ptr<WY>, 是初始化過的
26 shared_ptr<WY> p = ptr->shared_from_this();
27 ptr->get_shared_ptr();
28 wy.get_shared_ptr();
29 p = wy.shared_from_this();
30 }

24 行的 wy中的 weak_ptr沒有被初始化, 25行ptr是初始化過的

程序到28行的時候打印出   in get_shared_ptr  i = 6 之后異常退出, 即只要用 wy調用 shared_from_this 程序即異常退出

關於上面第二點中的源代碼剖析是針對 1-46-1來說的, 當我翻看以前版的源碼時, 發現並不是這樣實現的, 並沒_internal_accept_owner 這個函數, 所以我們只需記住的時boost為外提供的使用方式, 那就是要  shared_ptr<D>  pD的持用的 D, 其中的weak_this_才是初始化過的, 才可調用其 shared_from_this, 以這樣的方式   pD->shared_from_this()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM