C++核心準(zhǔn)則R.20: 使用unique_ptr或者shared_ptr表示所有權(quán)

R.20: Use?unique_ptr?or?shared_ptr?to represent ownership
R.20:?使用unique_ptr或者shared_ptr表示所有權(quán)
Reason(原因)
They can prevent resource leaks.
使用它們可以防止資源泄露。
Example(示例)
Consider(考慮以下代碼):
void f()
{
X x;
X* p1 { new X }; // see also ???
unique_ptr p2 { new X }; // unique ownership; see also ???
shared_ptr p3 { new X }; // shared ownership; see also ???
auto p4 = make_unique(); // unique_ownership, preferable to the explicit use "new"
auto p5 = make_shared(); // shared ownership, preferable to the explicit use "new"
}
This will leak the object used to initialize?p1?(only).
這段代碼中(只有)用來初始化p1的對象會(huì)發(fā)生泄露。
Enforcement(實(shí)施建議)
(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操作的返回值或者返回指針類型的函數(shù)調(diào)用的返回值被賦值給一個(gè)原始指針,發(fā)出警告。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r20-use-unique_ptr-or-shared_ptr-to-represent-ownership
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評論
圖片
表情
