首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则编译边学-F.27 使用shared_ptr<T>共享所有权

C++核心准则编译边学-F.27 使用shared_ptr<T>共享所有权

作者头像
面向对象思考
发布2020-03-25 15:25:49
4040
发布2020-03-25 15:25:49
举报

F.27: Use a shared_ptr<T> to share ownership

F.27 使用shared_ptr<T>共享所有权

Reason(原因)

Using std::shared_ptr is the standard way to represent shared ownership. That is, the last owner deletes the object.

使用std::shared_ptr是表现所有权共享的标准方式。使用这种方式时,最后一个所有者负责销毁对象。

Example(示例)
shared_ptr<const Image> im { read_image(somewhere) };

std::thread t0 {shade, args0, top_left, im};
std::thread t1 {shade, args1, top_right, im};
std::thread t2 {shade, args2, bottom_left, im};
std::thread t3 {shade, args3, bottom_right, im};

// detach threads
// last thread to finish deletes the image

译者注:代码首先构造了一个Image对象并使用shared_ptr管理。然后将它们传递个4个线程共享这个对象。这段代码会启动四个线程,然后(应该)退出im的作用域。当所有线程结束时,最后一个结束的线程负责销毁Image对象。

Note(注意)

Prefer a unique_ptr over a shared_ptr if there is never more than one owner at a time.shared_ptr is for shared ownership.

Note that pervasive use of shared_ptr has a cost (atomic operations on the shared_ptr's reference count have a measurable aggregate cost).

如果同一时刻永远不会有多于一个所有者的话,unique_ptr比shared_ptr更合适。

Alternative(可选方式)

Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.

让一个对象管理共享对象(例如范围对象)并且当所有用户都结束使用时(最好是隐式)销毁该(共享)对象。

Enforcement(实施建议)

(Not enforceable) This is a too complex pattern to reliably detect.

(不可执行)模式过于复杂以至于无法可靠地检查。

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

关注【面向对象思考】,轻松学习每一天!

有任何疑问,欢迎留言提问或讨论。


面向对象设计,面向对象编程,面向对象思考!

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.27: Use a shared_ptr<T> to share ownership
    • Reason(原因)
      • Example(示例)
        • Note(注意)
          • Alternative(可选方式)
            • Enforcement(实施建议)
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档