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

标签 c++

考虑以下代码:

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/

相关文章:

c++ - 为什么汇编输出中有这么多 iostream 的样板文件?

c++ - union 成员有一个重要的复制构造函数

c++ - 一个宏可以在不同的地方捕获一组异常吗?

c++ - 将 CString 传递给 fprintf

C++ 蛮力攻击函数不返回结果

c++ - 如何在 CLion 中编译子目录文件?

c++ - 当 ofstream 超出范围时偶尔出现 SEG FAULT

c++ - 编译 Cilk Plus 程序时遇到问题

c++ - Microsoft 支持的用于检索线程地址的 API 是什么

C++ 指针作用域