C++核心準則C.149:使用unique_ptr或者shared_ptr避免忘記銷毀使用...

C.149: Use?unique_ptr?or?shared_ptr?to avoid forgetting to delete objects created using new
C.149:使用unique_ptr或者shared_ptr避免忘記銷毀使用new創(chuàng)建的對象
Reason(原因)
Avoid resource leaks.
避免資源泄露。
Example(示例)
void use(int i)
{
auto p = new int {7}; // bad: initialize local pointers with new
auto q = make_unique(9); // ok: guarantee the release of the memory-allocated for 9
if (0 < i) return; // maybe return and leak
delete p; // too late
}
Enforcement(實施建議)
Flag initialization of a naked pointer with the result of a?new
提示使用new的結果初始化裸指針的情況。
Flag?delete?of local variable
標記銷毀局部變量的情況。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c149-use-unique_ptr-or-shared_ptr-to-avoid-forgetting-to-delete-objects-created-using-new
覺得本文有幫助?請分享給更多人。
關注【面向對象思考】輕松學習每一天!
面向對象開發(fā),面向對象思考!
評論
圖片
表情
