這個類很有意思,讓一個被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