enable_share_from_this功能介紹

來源:互聯網
上載者:User

這個類很有意思,讓一個被shared_ptr管理生命週期的類能夠在自己的成員函數內部訪問shared_ptr。有點繞。

舉個例子,下面的代碼在函數f內部通過this構造了shared_ptr對象,然後列印x_的值。

class B {public:    B(): x_(4) {        cout << "B::B()" << endl;    }        ~B() {        cout << "B::~B()" << endl;    }        void f() {        shared_ptr<B> p(this);        cout << p->x_ << endl;        //shared_from_this();    }    private:    int x_;};/* *  */int main(int argc, char** argv) {    shared_ptr<B> x(new B);    x->f();    return 0;}

編譯通過,但是運行結果:

B::B()4B::~B()B::~B()

兩次析構B對象,這是個災難。
現在試一下enable_shared_from_this:

class A : public enable_shared_from_this<A> {public:    A() {        cout << "A::A()" << endl;    }        ~A() {        cout << "A::~A()" << endl;    }        void f() {        //cout << shared_from_this()->x_ << endl; // this way is okay too        shared_ptr<A> p = shared_from_this();        cout << p->x_ << endl;    }    private:    int x_;};/* *  */int main(int argc, char** argv) {    shared_ptr<A> x(new A);    x->f();    return 0;}

運行結果:

A::A()0A::~A()

那麼,為什麼需要這樣做呢?在自己的類裡面訪問自己的成員,其實只是個範例程式碼,一定必要都沒有。

不過有一種可能,就是f函數需要返回自己的指標給調用者,難道這樣寫嗎?

A* f();

一個裸指標返回出去,失控了。誰也不知道調用者會幹什嗎?

比較聰明的方法是設計成:

shared_ptr<A> f()

好了,這就是為什麼我們需要enable_shared_from_this。

下面這篇文章介紹了enabled_shared_from_this幾種錯誤使用:
http://hi.baidu.com/cpuramdisk/item/7c2f8d77385e0f29d7a89cf0

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.