boost::enable_shared_from_this

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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值