前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.21:不需要共享所有权时应该使用unique_ptr而不是​shared_ptr

C++核心准则R.21:不需要共享所有权时应该使用unique_ptr而不是​shared_ptr

作者头像
面向对象思考
发布2020-04-14 16:39:15
4030
发布2020-04-14 16:39:15
举报

R.21: Prefer unique_ptr over shared_ptr unless you need to share ownership

R.21:不需要共享所有权时应该使用unique_ptr而不是shared_ptr

Reason(原因)

A unique_ptr is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count).

unique_ptr从概念上更简单,动作更加可预见(你知道析构动作什么时候发生)而且更快(不需要隐式维护使用计数)。

Example, bad(反面示例)

This needlessly adds and maintains a reference count.

不必要地增加和维护参照计数。

代码语言:javascript
复制
void f()
{
    shared_ptr<Base> base = make_shared<Derived>();
    // use base locally, without copying it -- refcount never exceeds 1
} // destroy base
Example(示例)

This is more efficient:

下面的代码更高效:

代码语言:javascript
复制
void f()
{
    unique_ptr<Base> base = make_unique<Derived>();
    // use base locally
} // destroy base
Enforcement(实施建议)

(Simple) Warn if a function uses a Shared_pointer with an object allocated within the function, but never returns the Shared_pointer or passes it to a function requiring a Shared_pointer&. Suggest using unique_ptr instead.

(简单)如果函数使用shared_ptr管理其内局部分配的对象,但是从来没有返回该智能指针或者将其传递个一个需要shared_ptr&的函数,发出警告。建议使用unique_ptr。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r21-prefer-unique_ptr-over-shared_ptr-unless-you-need-to-share-ownership


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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.21: Prefer unique_ptr over shared_ptr unless you need to share ownership
    • Example(示例)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档