C++核心準(zhǔn)則??ES.61:使用delete[]銷毀數(shù)組,使用delete銷毀對象

ES.61: Delete arrays using?delete[]?and non-arrays using?delete
ES.61:使用delete[]銷毀數(shù)組,使用delete銷毀對象
Reason(原因)
That's what the language requires and mistakes can lead to resource release errors and/or memory corruption.
這是C++語言的要求,如果用錯會導(dǎo)致資源釋放錯誤或者內(nèi)存破壞。
Example, bad(反面示例)
void f(int n)
{
auto p = new X[n]; // n default constructed Xs
// ...
delete p; // error: just delete the object p, rather than delete the array p[]
}Note(注意)
This example not only violates the?no naked?new?rule?as in the previous example, it has many more problems.
示例代碼不僅違反了前面示例中的禁止暴露的new規(guī)則,還有更多其他錯誤。
Enforcement(實(shí)施建議)
If the?new?and the?delete?are in the same scope, mistakes can be flagged.
如果new和delete同屬一個作用域,錯誤可以被標(biāo)記。
If the?new?and the?delete?are in a constructor/destructor pair, mistakes can be flagged.
如果new和delete分別位于構(gòu)造函數(shù)和析構(gòu)函數(shù),錯誤可以被標(biāo)記。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es61-delete-arrays-using-delete-and-non-arrays-using-delete
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
