前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.30: 只有在包含明确的生命周期语义时使用智能指针作参数

C++核心准则R.30: 只有在包含明确的生命周期语义时使用智能指针作参数

作者头像
面向对象思考
发布2020-04-14 16:41:32
5550
发布2020-04-14 16:41:32
举报

R.30: Take smart pointers as parameters only to explicitly express lifetime semantics

R.30: 只有在包含明确的生命周期语义时使用智能指针作参数

Reason(原因)

Accepting a smart pointer to a widget is wrong if the function just needs the widget itself. It should be able to accept any widget object, not just ones whose lifetimes are managed by a particular kind of smart pointer. A function that does not manipulate lifetime should take raw pointers or references instead.

如果一个函数只是需要一个部件本身,接受一个智能指针作参数是错误的。它应该可以接受所有部件对象,而不只是一个生命周期被按照特定方法管理的对象。不需要管理生命周期的函数应该使用原始的指针和引用。

Example, bad(反面示例)

代码语言:javascript
复制
// callee
void f(shared_ptr<widget>& w)
{
    // ...
    use(*w); // only use of w -- the lifetime is not used at all
    // ...
};

// caller
shared_ptr<widget> my_widget = /* ... */;
f(my_widget);

widget stack_widget;
f(stack_widget); // error
Example, good(范例)
代码语言:javascript
复制
// callee
void f(widget& w)
{
    // ...
    use(w);
    // ...
};

// caller
shared_ptr<widget> my_widget = /* ... */;
f(*my_widget);

widget stack_widget;
f(stack_widget); // ok -- now this works
Enforcement(实施建议)
  • (Simple) Warn if a function takes a parameter of a smart pointer type (that overloads operator-> or operator*) that is copyable but the function only calls any of: operator*, operator-> or get(). Suggest using a T* or T& instead.
  • (简单)如果一个函数使用了可拷贝的(重载了操作符->和操作符*的)智能指针类型的参数但是只是调用了运算符*、->或者get(),发出警告并建议使用T*或者T&。
  • Flag a parameter of a smart pointer type (a type that overloads operator-> or operator*) that is copyable/movable but never copied/moved from in the function body, and that is never modified, and that is not passed along to another function that could do so. That means the ownership semantics are not used. Suggest using a T* or T& instead.
  • 标记定义了(重载了操作符->和操作符*的)可拷贝/可移动智能指针类型的参数,但在函数体中却从未使用拷贝和移动功能,指针从未被修改也没有交给一个会那么做的函数的情况。那意味着所有权语义根本没有被使用。建议使用T*或者T&。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r30-take-smart-pointers-as-parameters-only-to-explicitly-express-lifetime-semantics


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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.30: Take smart pointers as parameters only to explicitly express lifetime semantics
  • Reason(原因)
    • Example, good(范例)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档