gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:49:45 25 4
gpt4 key购买 nike

假设我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com