前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.32:使用shared_ptr在无关线程之间共享所有权

C++核心准则CP.32:使用shared_ptr在无关线程之间共享所有权

作者头像
面向对象思考
发布2020-07-14 16:19:54
6710
发布2020-07-14 16:19:54
举报
CP.32: To share ownership between unrelated threads use shared_ptr CP.32:使用shared_ptr在无关线程之间共享所有权

Reason(原因)

If threads are unrelated (that is, not known to be in the same scope or one within the lifetime of the other) and they need to share free store memory that needs to be deleted, a shared_ptr (or equivalent) is the only safe way to ensure proper deletion.

如果线程之间没有关联(即,无法断定处于相同的作用域,或者一个线程处于另一个线程的生命周期中)而且共享需要删除的自由存贮内存,share_ptr(或等价物)是可以保证安全、正确地销毁内存的唯一方法。

Example(示例)

代码语言:javascript
复制
???
Note(注意)
  • A static object (e.g. a global) can be shared because it is not owned in the sense that some thread is responsible for its deletion.
  • 没有任何线程有责任销毁静态对象(例如全局变量),从这个角度来讲静态对象是没有所有者的。因此可以说静态变量是可以共享的。
  • An object on free store that is never to be deleted can be shared.
  • 存在于永远不会被销毁的自由存储上的对象可以共享。
  • An object owned by one thread can be safely shared with another as long as that second thread doesn't outlive the owner.
  • 只要第二个线程的生命期间没有长于所有者线程,那么一个线程拥有的对象就可以安全的分享给第二个线程。
Enforcement(实施建议)

???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp31-pass-small-amounts-of-data-between-threads-by-value-rather-than-by-reference-or-pointer

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Note(注意)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档