c++ - 这种删除是否会破坏每个数组对象?

标签 c++ language-lawyer

假设我使用 new 的变体来返回指向数组的指针:

class Type { /* ... */ };

typedef Type Type_42[1][42];
Type (*x)[42] = new Type_42;

因为我用new来创建,所以我用delete来销毁:

delete x;

是否预计将调用 42 个对象的每个析构函数?

最佳答案

delete[] 必须用于数组,delete 用于非数组。由于 x 是指向数组的指针,因此您必须使用 delete[]。引文是 [expr.delete]/2。第一个注释使这一点变得非常清楚。

If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section. In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined. In the second alternative (delete array), the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression. If not, the behavior is undefined. [ Note: this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression.end note ] [ Note: a pointer to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness (5.2.11) of the pointer expression before it is used as the operand of the delete-expression.end note ]

关于c++ - 这种删除是否会破坏每个数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37171370/

相关文章:

c++ - 我如何在 vc6.0 中使用 Imagemagick 库?

c++ - 当发生构造函数故障时,必须进行哪些清理工作?

c++ - POSIX 线程,将多个参数传递给具有结构的函数

c++ - 用C++代码返回对象是什么意思?

c++ - SDL2 无法创建窗口,因为找不到匹配的 GLX 视觉对象

C++11 替代 boost::checked_delete

c++ - 在内联函数的定义中使用 constexpr 变量时可能发生的 ODR 违规(在 C++14 中)

c++ - 如何在不指定数组大小的情况下声明数组,但在 C++ 的类中使用初始化程序?

c++ - Clang 中不明确的运算符重载

c - 指针的 memcpy 与赋值相同吗?