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

Calling delete on variable allocated on the stack(在堆栈上分配的变量上调用 delete)
本文介绍了在堆栈上分配的变量上调用 delete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

忽略编程风格和设计,对分配在堆栈上的变量调用 delete 是否安全"?

Ignoring programming style and design, is it "safe" to call delete on a variable allocated on the stack?

例如:

   int nAmount;
   delete &nAmount;

class sample
{
public:
    sample();
    ~sample() { delete &nAmount;}
    int nAmount;
}

推荐答案

否,在堆栈分配的变量上调用 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.

这篇关于在堆栈上分配的变量上调用 delete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)