【Boost】boost::shared_from_this值得注意的地方

來源:互聯網
上載者:User

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這種方式,也決不要傳遞裸指標。   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.