前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则编译边学-F.26 使用unique_ptr<T>代替指针传递所有权

C++核心准则编译边学-F.26 使用unique_ptr<T>代替指针传递所有权

作者头像
面向对象思考
发布2020-03-25 15:25:28
3220
发布2020-03-25 15:25:28
举报
文章被收录于专栏:C++核心准则原文翻译

F.26: Use a unique_ptr<T> to transfer ownership where a pointer is needed

F.26 使用unique_ptr<T>代替指针传递所有权

Reason(原因)

Using unique_ptr is the cheapest way to pass a pointer safely.

使用unique_ptr是成本最低的安全地传递指针的方式。

See also: C.50 regarding when to return a shared_ptr from a factory.

参见:C.50 关于什么时候从工厂返回shared_ptr。

Example(示例)

代码语言:javascript
复制
unique_ptr<Shape> get_shape(istream& is)  // assemble shape from input stream
{
    auto kind = read_header(is); // read header and identify the next shape on input
    switch (kind) {
    case kCircle:
        return make_unique<Circle>(is);
    case kTriangle:
        return make_unique<Triangle>(is);
    // ...
    }
}

译者注:关于unique_ptr,可以参照:https://mp.weixin.qq.com/s/wgc8p1Pw9GD5LIx1C33wxQ

Note(注意)

You need to pass a pointer rather than an object if what you are transferring is an object from a class hierarchy that is to be used through an interface (base class).

如果你希望传递的是将会通过(基类)接口使用的,继承关系中的类对象时,应该传递指针而不是对象。

译者注:这句话的意思应该是:如果只是传递一个用于调用的接口,直接使用指针式最好的方式。

Enforcement(实施建议)

(Simple) Warn if a function returns a locally allocated raw pointer. Suggest using either unique_ptr or shared_ptr instead.

(简单)如果函数返回本地分配的裸指针,报警并建议使用unique_ptr或者shared_ptr代替。

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

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

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


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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.26: Use a unique_ptr<T> to transfer ownership where a pointer is needed
    • Reason(原因)
      • Example(示例)
        • Note(注意)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档