析构函数如何执行?

How Destructor executes?

我在Destructor上做了实践,但是当编译这个程序时,我不知道为什么输出不是我想的那样。

#include <iostream>
using namespace std;
class aaa
{
   private:
   static int x;
   int code;
   public:
   /*after constructor executes 3 times the value of "code" becomes 103*/
  aaa()   
  {
    code=x;
    cout<<"Default Constructor"<<endl;
    x++;
  } 
  ~aaa() 
  {
    cout<<"Destructor of "<<code<<endl;
  } 
};
int aaa::x=101;
int main() 
{
   aaa *p;
   p=new aaa[3];
   delete []p;
   return 0;
 } 

输出为:

Default Constructor
Default Constructor
Default Constructor
Destructor of 103
Destructor of 102 
Destructor of 101

虽然我以为会是这样:

101
102
103

析构以构造的相反顺序发生,这就是为什么您会看到 103 的析构函数首先被调用的原因。

即当您分配数组时,new[] 沿一个方向构造对象,然后当您调用 delete[] 时,对象从数组末尾开始销毁。

有关此行为,请参阅

I don't know why the output not come as I thought.

因为对象的破坏顺序与构造相反:首先构造,最后破坏。

析构函数的调用顺序与构造函数的调用相反,这解释了您看到的行为。

因此,当您使用 new[] 为数组动态分配内存时,构造函数将按自然顺序(您期望的顺序)调用,但是当调用 delete[] 以释放该内存时,数组的每个元素都以相反的顺序被破坏。

中阅读更多内容

What happens if i write delete p instead of delete []p, so ho many times Destructor is called?

C++ 要求您使用 delete[] 删除数组,使用 delete 删除非数组。所以我无法回答。在 Delete and delete [] are the same when deleting arrays?

中阅读更多内容

析构函数的调用顺序与对象初始化相反,对于被 delete[] 销毁的数组也是如此:

[expr.delete/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 [class.base.init]).