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(考慮以下代碼):
<code>class X {
// ...
void* operator new(size_t s);
void operator delete(void*);
// ...
};/<code>
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
覺得本文有幫助?請分享給更多人。
關注【面向對象思考】輕鬆學習每一天!
面向對象開發,面向對象思考!
閱讀更多 面向對象思考 的文章