使用 delete
而不是 delete[]
有什么问题?
在分配和释放数组的背后是否发生了一些特别的事情?
为什么会不同于malloc
和free?
最佳答案
使用 new[]
创建的对象必须使用 delete[]
。使用 delete
在数组上是未定义的。
使用 malloc 和 free 时,情况会更简单。只有 1 个函数可以释放您分配的数据,也没有调用析构函数的概念。混淆只是因为 delete[]
和 delete 看起来相似。实际上它们是两个完全不同的功能。
使用 delete 不会调用正确的函数来删除内存。它应该调用 delete[](void*)
但它却调用 delete(void*)
。出于这个原因,您不能依赖使用 delete
来分配由 new[]
[16.13] Can I drop the
[]
when deleteing array of some built-in type (char, int, etc)?No!
Sometimes programmers think that the
[]
in thedelete[] p
only exists so the compiler will call the appropriate destructors for all elements in the array. Because of this reasoning, they assume that an array of some built-in type such aschar
orint
can bedelete
d without the[]
. E.g., they assume the following is valid code:void userCode(int n) { char* p = new char[n]; ... delete p; // ← ERROR! Should be delete[] p ! }
But the above code is wrong, and it can cause a disaster at runtime. In particular, the code that's called for
delete p
isoperator delete(void*)
, but the code that's called fordelete[] p
isoperator delete[](void*)
. The default behavior for the latter is to call the former, but users are allowed to replace the latter with a different behavior (in which case they would normally also replace the corresponding new code in operatornew[](size_t)
). If they replaced thedelete[]
code so it wasn't compatible with the delete code, and you called the wrong one (i.e., if you saiddelete p
rather thandelete[] p
), you could end up with a disaster at runtime.
为什么delete[]
首先存在?
无论你做 x 还是 y:
char * x = new char[100];
char * y = new char;
两者都存储在 char *
类型变量中。
我认为 delete
和 delete[]
的决定的原因与一长串有利于 C++ 效率的决定有关。这样就没有强制的价格来查找正常删除操作需要删除多少。
拥有 2 个 new
和 new[]
似乎只有 delete
和 delete[]
才合乎逻辑对称。
关于c++ - 为什么数组有特殊的new和delete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/659270/