weak_ptr 和enable_shared_from_this

weak_ptr

std::weak_ptr 是一种智能指针,它对被 std::shared_ptr 管理的对象存在非拥有性(“弱”)引用。在访问所引用的对象前必须先转换为 std::shared_ptr。
std::weak_ptr 用来表达临时所有权的概念:当某个对象只有存在时才需要被访问,而且随时可能被他人删除时,可以使用 std::weak_ptr 来跟踪该对象。需要获得临时所有权时,则将其转换为 std::shared_ptr,此时如果原来的 std::shared_ptr 被销毁,则该对象的生命期将被延长至这个临时的 std::shared_ptr 同样被销毁为止。
此外,std::weak_ptr 还可以用来避免 std::shared_ptr 的循环引用。
用一句stackover flow 上高票回答来通俗的解释就是:

This is exactly what a weak pointer does – it allows you to locate an object if it’s still around, but doesn’t keep it around if nothing else needs it.

weak_ptr不会增加引用,当没有其他shared_ptr管理这个对象的时候weak_ptr不会阻止这个对象的释放,weak_ptr 只是单纯的帮助用户来定位这个对象的位置。

通过一段代码加上注释来解释一下这个问题:

#include <iostream>
#include <memory>

std::weak_ptr<int> gw;

void f()
{
    if (auto spt = gw.lock()) { // 使用之前必须复制到 shared_ptr
    std::cout << *spt << "\n";
    }
    else {
        std::cout << "gw is expired\n";
    }
}

int main()
{
    {
        auto sp = std::make_shared<int>(42);
        gw = sp;
        f();
    }

    f();
}

上面的代码中,gw是全局weak_ptr,sp是局部shared_ptr.在局部作用域中sp尚未被销毁。所以第一次调用f()时,gw能够通过lock获得一个shared_ptr来使用这个对象,注意,weak_ptr并未重载 * , ->这些操作符。 所以,要使用这个对象的时候必须先lock。第二次调用f()后sp被销毁,无法再次lock到这个对象。

接下来是enable_shared_from_this

enable_shared_from_this是做什么的呢

int *ip = new int;
shared_ptr<int> sp1(ip);
shared_ptr<int> sp2(ip);

先看这段代码中存在的问题,这两个shared_ptr sp1和sp2不知道对方的存在,当sp1,sp2离开作用域的时候,会释放两次对象,产生错误。类似的是,当你需要在一个成员函数中返回使用this指针构造的shard_ptr对象时,不能随手像下面这么写:

struct S
{
  shared_ptr<S> dangerous()
  {
     return shared_ptr<S>(this);   // don't do this!
  }
};

int main()
{
   shared_ptr<S> sp1(new S);
   shared_ptr<S> sp2 = sp1->dangerous();
   return 0;
}

与上面相同的是,sp2同样不知道sp1这个shared_ptr,所以会导致释放两次对象。

正确的用法应该是引出enable_shared_from_this:

struct S : enable_shared_from_this<S>
{
  shared_ptr<S> not_dangerous()
  {
    return shared_from_this();
  }
};

int main()
{
   shared_ptr<S> sp1(new S);
   shared_ptr<S> sp2 = sp1->not_dangerous();
   return 0;
}

在使用enable_shared_from_this时注意调用shared_from_this()的对象必须被一个shared_ptr拥有。
不能下面这样调用:

int main()
{
   S *p = new S;
   shared_ptr<S> sp2 = p->not_dangerous();     // don't do this
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值