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

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

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