C++中怎么使用shared_ptr<T>共享所有权

发布时间:2021-11-24 11:55:35 作者:iii
来源:亿速云 阅读:211

这篇文章主要介绍“C++中怎么使用shared_ptr<T>共享所有权”,在日常操作中,相信很多人在C++中怎么使用shared_ptr<T>共享所有权问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++中怎么使用shared_ptr<T>共享所有权”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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.

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

到此,关于“C++中怎么使用shared_ptr<T>共享所有权”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. C++中的伪共享是什么
  2. C++中怎么实现共享内存

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:c++容易混淆的点有哪些

下一篇:C++11随机数库怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》