c++ - 为什么数组有特殊的new和delete?

标签 c++ arrays memory-management new-operator

使用 delete 而不是 delete[] 有什么问题?

在分配和释放数组的背后是否发生了一些特别的事情?

为什么会不同于malloc和free?

最佳答案

使用 new[] 创建的对象必须使用 delete[]。使用 delete 在数组上是未定义的。

使用 malloc 和 free 时,情况会更简单。只有 1 个函数可以释放您分配的数据,也没有调用析构函数的概念。混淆只是因为 delete[] 和 delete 看起来相似。实际上它们是两个完全不同的功能。

使用 delete 不会调用正确的函数来删除内存。它应该调用 delete[](void*) 但它却调用 delete(void*)。出于这个原因,您不能依赖使用 delete 来分配由 new[]

分配的内存

See this C++ FAQ

[16.13] Can I drop the [] when deleteing array of some built-in type (char, int, etc)?

No!

Sometimes programmers think that the [] in the delete[] 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 as char or int can be deleted 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 is operator delete(void*), but the code that's called for delete[] p is operator 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 operator new[](size_t)). If they replaced the delete[] code so it wasn't compatible with the delete code, and you called the wrong one (i.e., if you said delete p rather than delete[] p), you could end up with a disaster at runtime.

为什么delete[]首先存在?

无论你做 x 还是 y:

 char * x = new char[100]; 
 char * y = new char;

两者都存储在 char * 类型变量中。

我认为 deletedelete[] 的决定的原因与一长串有利于 C++ 效率的决定有关。这样就没有强制的价格来查找正常删除操作需要删除多少。

拥有 2 个 newnew[] 似乎只有 deletedelete[] 才合乎逻辑对称。

关于c++ - 为什么数组有特殊的new和delete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/659270/

相关文章:

ios - 全局变量神秘丢失内存?

arrays - 为什么 Swift 编译器无法确定混合类型数组中元素的类型?

ios - 在 Swift 中使用高阶函数更新数组值

c - C 中的加密数组

c++ - 在函数中再分配一个变量会大大增加执行时间

java - 在网格中显示大量图像

c++ - 在 Windows x64 上设置 openssl 时找不到 libeay32.lib 和 ssleay32.lib 文件

c++ - 动态分配对象

c++ - C++ 中重载的指针问题?

c++ - 获取 C++ double 函数以在满足特定条件时报告消息而不是返回数字