enable_shared_from_this小例子

enable_shared_from_this是针对类中数据传出shared_ptr出现多次析构而设计的

class Test  //这种情况会析构两次,有段错误
{
public:
    ~Test() { cout << "析构了!" << endl; }
    shared_ptr<Test> GetThis()
    {
        return shared_ptr<Test>(this);
/    }
};

int main() {
    shared_ptr<Test> p(new Test());
    shared_ptr<Test> q = p->GetThis();
}

上段代码中有p通过GetThis将this传给q,因此引用指数为2,但数据只有一份,最后析构两次导致出错

对上段代码用enable_shared_from_this改造后:

class Test :public enable_shared_from_this<Test>
{
public:
    ~Test() { cout << "析构了!" << endl; }
    shared_ptr<Test> GetThis()
    {
        return shared_from_this();
    }
};

int main() {
    shared_ptr<Test> p(new Test());
    shared_ptr<Test> q = p->GetThis();
}

通过调用shared_from_this()后,析构只用了一次,不会出现段错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值