您的位置 首页 > 腾讯云社区

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

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.

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

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

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

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

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

---来自腾讯云社区的---面向对象思考

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: