R.20: Use unique_ptr or shared_ptr to represent ownership
R.20: 使用unique_ptr或者shared_ptr表示所有權
Reason(原因)
They can prevent resource leaks.
使用它們可以防止資源泄露。
Example(示例)
Consider(考慮以下代碼):
void f()
{
X x;
X* p1 { new X }; // see also ???
unique_ptr<T> p2 { new X }; // unique ownership; see also ???
shared_ptr<T> p3 { new X }; // shared ownership; see also ???
auto p4 = make_unique<X>(); // unique_ownership, preferable to the explicit use "new"
auto p5 = make_shared<X>(); // shared ownership, preferable to the explicit use "new"
}
This will leak the object used to initialize p1 (only).
這段代碼中(只有)用來初始化p1的對象會發生泄露。
Enforcement(實施建議)
(Simple) Warn if the return value of new or a function call with return value of pointer type is assigned to a raw pointer.
(簡單)如果new操作的返回值或者返回指針類型的函數調用的返回值被賦值給一個原始指針,發出警告。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r20-use-unique_ptr-or-shared_ptr-to-represent-ownership
覺得本文有幫助?歡迎點贊並分享給更多的人。
閱讀更多更新文章,請關注微信公衆號【面向對象思考】