智能指针weak_ptr

智能指针weak_ptr主要用来协助shared_ptr。不参与引用计数,但是有以下好处:

1 打破递归的依赖关系

2 使用一个共享的资源但是不要所有权,不添加引用计数

3 避免悬空指针。

使用方法有二:

// 方法一
boost::shared_ptr<std::string> sp(new std::string("method1");
// 从shared_ptr构建出来
boost::weak_ptr<std::string>wp(sp);
// 再从shared_ptr获取回去
boost::shared_ptr<std::string> p = wp.lock();


 

// 方法二
boost::shared_ptr<std::string> sp(new std::string("method1");
// 从shared_ptr构建出来
boost::weak_ptr<std::string>wp(sp);
// 再从shared_ptr获取回去
boost::shared_ptr<std::string> p(wp);


 注意:各个智能指针都设计的尽量与STL兼容,但是还有一些问题。比如equal_to中比较string的示例就会导致出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值