如果在 C++ 中对数组应用“delete”而不是“delete[]”,则会造成内存泄漏,因为只会删除第一个元素。但是,如果您不小心将“delete[]”应用于非数组指针,会发生什么情况?例如(只是一个玩具示例):
class X {
void foo()
{
X* x = new X();
delete[] x; // What happens here?
}
};
它有什么坏处吗?如果是这样,有什么危害?
最佳答案
If you apply "delete" instead of "delete[]" to an array in C++, then you will create a memory leak because only the first element will be deleted.
这并不总是正确的。因为new、new[]、delete、delete[]操作符也可以重载,使用delete代替delete[](或相反)可以产生巨大的不同。
此外,一些编译器使用过度分配技术描述here .因此,在非数组指针上应用 delete[] 会导致未定义的行为。
关于c++ - 如果将 delete[] 应用于非数组指针会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27771199/