您的位置:首页 > 其它

boost::enable_shared_from_this

2016-07-20 10:55 232 查看
boost::enable_shared_from_this


这个类能够让一个被
shared_ptr
管理生命周期的类能够在自己的成员函数内部使用自己的
shared_ptr


在什么场景下需要使用一个
shared_ptr
呢?直接使用this指针不行吗?

想象一下这样的场景:在类中发起一个异步操作,回调函数callback在被调用时要保证发起操作的对象仍然存在。那么使用this是不合适的,因为它有可能已经析构了。而使用
shared_ptr
则能够保证对象的引用计数至少为1,这也就保证了对象仍然有效。

举个例子:

在不使用
boost::enable_shared_from_this
时,在自己的成员函数获取自身的
shared_ptr
成了问题,如下例所示:

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

using namespace std;

class Foo {
public:
Foo() : n_(8) { cout << "ctor" << endl; }
~Foo(){ cout << "dtor" << endl; }
void DoSomething()
{
boost::shared_ptr<Foo> sp(this);
cout << n_ << endl;
}
private:
int n_;
};

int main()
{
boost::shared_ptr<Foo> f(new Foo);
f->DoSomething();
return 0;
}


这种用法是错误的,一个对象被两个智能指针管理,很明显,析构函数会被调用两次:

ctor
8
dtor
dtor


这时需要使用
boost::enable_shared_from_this


class Foo2 : public boost::enable_shared_from_this<Foo2> {
public:
Foo2() : n_(8) { cout << "ctor" << endl; }
~Foo2(){ cout << "dtor" << endl; }
void DoSomething()
{
boost::shared_ptr<Foo2> sp = shared_from_this();
cout << n_ << endl;
}

boost::shared_ptr<Foo2> GetPointer()
{
return shared_from_this();
}

private:
int n_;
};

int main()
{
boost::shared_ptr<Foo2> f(new Foo2);
f->DoSomething();

cout << "use count:" << f.use_count() << endl;
boost::shared_ptr<Foo2> t = f->GetPointer();
cout << "use count:" <<f.use_count() << endl;

return 0;
}


输出:

ctor
8
use count:1
use count:2
dtor
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: