gpt4 book ai didi

c++ - 堆栈/堆分配数组的销毁顺序

转载 作者:行者123 更新时间:2023-11-30 02:38:07 26 4
gpt4 key购买 nike

考虑以下代码:

struct A{...};

A a[100];
A* pa = new A[100];
delete[] pa;

a/pa 元素的销毁顺序是由标准定义的还是实现定义的(对于第二种情况 operator delete[] 不是用户定义的)。

最佳答案

数组元素将按构造的相反顺序被销毁,元素 99 首先被销毁,然后是元素 989796... 等等,元素 0 是最后一个。

参见 isocpp析构函数常见问题解答。

来自最新草案的5.3.5.6:

If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

还有 12.6.3 中的这个(它不是特定于 delete 关键字):

When an array of class objects is initialized (either explicitly or implicitly) and the elements are initialized by constructor, the constructor shall be called for each element of the array, following the subscript order; see 8.3.4. [ Note: Destructors for the array elements are called in reverse order of their construction. — end note ]

关于c++ - 堆栈/堆分配数组的销毁顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31101854/

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