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

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(反面示例)

// 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(范例)

// 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

 


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章