考虑以下代码:
struct A{...};
A a[100];
A* pa = new A[100];
delete[] pa;
a
/pa
元素的销毁顺序是由标准定义还是由实现定义(对于第二种情况 operator delete[]
不是用户定义的)。
最佳答案
数组元素将以与构造相反的顺序被破坏,元素 99
首先被破坏,然后是元素 98
、97
、 96
...等等,元素 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/