前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.22: 使用make_shared()构建共享shared_ptr

C++核心准则R.22: 使用make_shared()构建共享shared_ptr

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

R.22: Use make_shared() to make shared_ptrs

R.22: 使用make_shared()构建共享shared_ptr

Reason(原因)

If you first make an object and then give it to a shared_ptr constructor, you (most likely) do one more allocation (and later deallocation) than if you use make_shared() because the reference counts must be allocated separately from the object.

如果你首先构建一个对象然后将它交给shared_ptr的构造函数,和使用make_shared的情况相比,你(很有可能)多执行了一次分配动作(和将要发生的一次释放动作)。因为参照计数(此处应该是shared_ptr对象,译者注)的分配必须和对象的分配分别进行。

Example(示例)

Consider(考虑下面的代码):

代码语言:javascript
复制
shared_ptr<X> p1 { new X{2} }; // bad
auto p = make_shared<X>(2);    // good

The make_shared() version mentions X only once, so it is usually shorter (as well as faster) than the version with the explicit new.

make_shared方式只是用一次X对象,因此它通常比显式调用new的代码更简短(执行也更高效)。

Enforcement(实施建议)

(Simple) Warn if a shared_ptr is constructed from the result of new rather than make_shared.

(简单)如果使用new的结果构造shared_ptr而不是make_shared,报警。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r22-use-make_shared-to-make-shared_ptrs


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

关注微信公众号【面向对象思考】轻松学习每一天!

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

在看

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.22: Use make_shared() to make shared_ptrs
    • Reason(原因)
      • Example(示例)
        • Enforcement(实施建议)
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档