假设我使用 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 ofdelete
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 bynew
, not the syntax of the new-expression. — end note ] [ Note: a pointer to aconst
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/