C.149: Use unique_ptr or shared_ptr to avoid forgetting to delete objects created using new
C.149:使用unique_ptr或者shared_ptr避免忘記銷燬使用new創建的對象
Reason(原因)
Avoid resource leaks.
避免資源泄露。
Example(示例)
void use(int i)
{
auto p = new int {7}; // bad: initialize local pointers with new
auto q = make_unique<int>(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
覺得本文有幫助?歡迎點贊並分享給更多的人。
閱讀更多更新文章,請關注微信公衆號【面向對象思考】