且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在堆栈上分配的变量上调用 delete

更新时间:2023-11-13 14:02:40

,在堆栈分配的变量上调用 delete 是不安全的.你应该只对 new 创建的东西调用 delete.

No, it is not safe to call delete on a stack-allocated variable. You should only call delete on things created by new.

  • 对于每个 malloccalloc,应该只有一个 free.
  • 对于每个 new,应该恰好有一个 delete.
  • 对于每个 new[],应该恰好有一个 delete[].
  • 对于每个堆栈分配,不应有明确的释放或删除.在适用的情况下,会自动调用析构函数.
  • For each malloc or calloc, there should be exactly one free.
  • For each new there should be exactly one delete.
  • For each new[] there should be exactly one delete[].
  • For each stack allocation, there should be no explicit freeing or deletion. The destructor is called automatically, where applicable.

一般情况下,您不能混合搭配其中任何一种,例如没有 free-ing 或 delete[]-ing new 对象.这样做会导致未定义的行为.

In general, you cannot mix and match any of these, e.g. no free-ing or delete[]-ing a new object. Doing so results in undefined behavior.