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>&参数表示函数重置智能指针


分享到:


相關文章: