前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.24: 使用std::weak_ptr打破share_ptrs造成的循环

C++核心准则R.24: 使用std::weak_ptr打破share_ptrs造成的循环

作者头像
面向对象思考
发布2020-04-14 16:41:08
5020
发布2020-04-14 16:41:08
举报

R.24: Use std::weak_ptr to break cycles of shared_ptrs

R.24: 使用std::weak_ptr打破share_ptrs造成的循环

Reason(原因)

shared_ptr's rely on use counting and the use count for a cyclic structure never goes to zero, so we need a mechanism to be able to destroy a cyclic structure.

shared_ptr依靠使用计数动作,而循环构造(例如相互持有shared_ptr,译者注)可能导致计数永远不归零,因此我们需要一种机制打破这种循环。

Example(示例)

#include <memory>

class bar;

class foo
{
public:
  explicit foo(const std::shared_ptr<bar>& forward_reference)
    : forward_reference_(forward_reference)
  { }
private:
  std::shared_ptr<bar> forward_reference_;
};

class bar
{
public:
  explicit bar(const std::weak_ptr<foo>& back_reference)
    : back_reference_(back_reference)
  { }
  void do_something()
  {
    if (auto shared_back_reference = back_reference_.lock()) {
      // Use *shared_back_reference
    }
  }
private:
  std::weak_ptr<foo> back_reference_;
};
Note(注意)

??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.) ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it. You could "temporarily share ownership" simply by using another shared_ptr.

???(HS:很多人说“打破循环”,我却觉得“暂时分享所有权”才是关键)???(BS:打破循环是必须做的事,临时分享所有权是做这件事的方法。你可以简单地使用另外一个shared_ptr“暂时分享所有权”。

Enforcement(实施建议)

??? probably impossible. If we could statically detect cycles, we wouldn't need weak_ptr

??? 差不多不可能。如果你能静态检查到循环,我们将不需要weak_ptr。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r23-use-make_unique-to-make-unique_ptrs


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.24: Use std::weak_ptr to break cycles of shared_ptrs
  • Reason(原因)
    • Note(注意)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档