enable share from this功能介紹
阿新 • • 發佈:2018-11-17
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
這個類很有意思,讓一個被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