前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​​ES.61:使用delete[]销毁数组,使用delete销毁对象

C++核心准则​​ES.61:使用delete[]销毁数组,使用delete销毁对象

作者头像
面向对象思考
发布2020-05-25 16:29:56
8790
发布2020-05-25 16:29:56
举报

ES.61: Delete arrays using delete[] and non-arrays using delete

ES.61:使用delete[]销毁数组,使用delete销毁对象

Reason(原因)

That's what the language requires and mistakes can lead to resource release errors and/or memory corruption.

这是C++语言的要求,如果用错会导致资源释放错误或者内存破坏。

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规则,还有更多其他错误。

Enforcement(实施建议)
  • If the new and the delete are in the same scope, mistakes can be flagged.
  • 如果new和delete同属一个作用域,错误可以被标记。
  • If the new and the delete are in a constructor/destructor pair, mistakes can be flagged.
  • 如果new和delete分别位于构造函数和析构函数,错误可以被标记。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es61-delete-arrays-using-delete-and-non-arrays-using-delete

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.61: Delete arrays using delete[] and non-arrays using delete
  • Reason(原因)
    • Note(注意)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档