C++核心准则R.32: 通过 unique_ptr(widget)类型参数表示函数试图获取widget的所有权

R.32: Take a unique_ptr<widget> parameter to express that a function assumes ownership of a widget

R.32: 通过unique_ptr<widget>类型参数表示函数试图获取widget的所有权

 

Reason(原因)

Using unique_ptr in this way both documents and enforces the function call's ownership transfer.

以这种方式使用unique_ptr可以从文档和实现两个方面强制进行所有权的移交。

 

Example(示例)

void sink(unique_ptr<widget>); // takes ownership of the widget

void uses(widget*);            // just uses the widget

Example, bad(反面示例)

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

Enforcement(实施建议)

  • (Simple) Warn if a function takes a Unique_pointer<T> 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<T>参数,却没有对它赋值,或者在至少一条代码路径上调用了reset,报警。建议使用T*或者T&代替。

  • (Simple) ((Foundation)) Warn if a function takes a Unique_pointer<T> parameter by reference to const. Suggest taking a const T* or const T& instead.

  • (简单)((基本)) 如果一个函数以常量引用方式使用Unique_pointer<T>参数,建议使用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

 


 

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

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

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