shared_from_this()在一個類中需要傳遞類對象本身shared_ptr的地方使用shared_from_this函數來獲得指向自身的shared_ptr,它是enable_shared_from_this<T>的成員函數,返回shared_ptr<T>。
首先需要注意的是:這個函數僅在shared_ptr<T>的建構函式被調用之後才能使用。原因是enable_shared_from_this::weak_ptr並不在enable_shared_from_this<T>建構函式中設定,而是在shared_ptr<T>的建構函式中設定。
a) 如下代碼是錯誤的:
class D:public boost::enable_shared_from_this<D>{public: D() { boost::shared_ptr<D> p=shared_from_this(); }};
原因很簡單,在D的建構函式中雖然可以保證enable_shared_from_this<D>的建構函式已經被調用,但正如前面所說,weak_ptr還沒有設定。
b) 如下代碼也是錯誤的:
class D:public boost::enable_shared_from_this<D>{public: void func() { boost::shared_ptr<D> p=shared_from_this(); }};void main(){ D d; d.func();}
錯誤原因同上。
c) 如下代碼是正確的:
void main(){ boost::shared_ptr<D> d(new D); d->func();}
這裡boost::shared_ptr<D> d(new D)實際上執行了3個動作:
1. 首先調用enable_shared_from_this<D>的建構函式;
2. 其次調用D的建構函式;
3. 最後調用shared_ptr<D>的建構函式。
是第3個動作設定了enable_shared_from_this<D>的weak_ptr,而不是第1個動作。這個地方是很違背c++常理和邏輯的,必須小心。
結論是:不要在建構函式中使用shared_from_this;其次,如果要使用shared_ptr,則應該在所有地方均使用,不能使用D d這種方式,也決不要傳遞裸指標。