ptr<widget>&參數表示函數重置智能指針

C++核心準則R.33: unique_ptr<widget>&參數表示函數重置智能指針

R.33: Take a unique_ptr<widget>& parameter to express that a function reseats the widget/<widget>

R.33: 表達函數會重置widget時,使用unique_ptr<widget>&作參數。/<widget>

Reason(原因)

Using unique_ptr in this way both documents and enforces the function call's reseating semantics.

以這種方式使用unique_ptr可以從文檔和實現兩個方面強制函數調用的重置語義。

Note(注意)

"reseat" means "making a pointer or a smart pointer refer to a different object."

“重置”的意思是使指針或者智能指針參照另外一個對象。

Example(示例)

<code>void reseat(unique_ptr<widget>&); // "will" or "might" reseat pointer/<widget>/<code>

Example, bad(反面示例)

<code>void thinko(const unique_ptr<widget>&); // usually not what you want/<widget>/<code>

Enforcement(實施建議)

  • (Simple) Warn if a function takes a Unique_pointer parameter by lvalue reference and does not either assign to it or call reset() on it on at least one code path. Suggest taking a T* or T& instead.
  • (簡單)如果一個函數以左值引用方式使用了Unique_pointer類型參數,卻沒有至少一個代碼路徑上對它賦值或者調用reset方法,提出警告。建議改用T*或者T& 。
  • (Simple) ((Foundation)) Warn if a function takes a Unique_pointer parameter by reference to const. Suggest taking a const T* or const T& instead.
  • (簡單)((基礎))如果一個函數以常量引用形式使用了Unique_pointer參數,提出警告。建議改用const T* 或 const T&。

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r32-take-a-unique_ptrwidget-parameter-to-express-that-a-function-assumes-ownership-of-a-widget


覺得本文有幫助?請分享給更多人。

關注微信公眾號【面向對象思考】輕鬆學習每一天!

面向對象開發,面向對象思考!

C++核心準則R.33: unique_ptr<widget>&參數表示函數重置智能指針


分享到:


相關文章: