为什么这个程序中的析构函数被调用两次

Why is the destructor in this program called twice?

本文关键字:调用 两次 析构函数 程序 为什么      更新时间:2023-10-16

是的,我知道这个问题已经被问了很多次了,我试图理解以前关于这个问题的帖子(并相信我已经尝试过),但我真的无法掌握这个概念。

在下面的程序中,创建了类 A 数组 a,并且为数组中的每个相应元素调用了四次默认构造函数。这部分我得到了。指针 p 被分配给类对象数组 a。我想 p 现在指向数组中的第一个元素。现在这就是我迷路的地方。析构函数被调用 4 次。我读过很多解释,但它们似乎只会让我更加困惑。我真的只是想简单解释一下为什么会发生这种情况。

如果再次问这个问题很烦人,我很抱歉(尽管我确信我不会是最后一个),但那些愿意的人的任何帮助将不胜感激。

我的程序加上输出:

#include <iostream.h>
  class A
  {
  public:
      A(int i)
      {  a=i;  }
      A()
      {
         a=0;
         cout<<"Default constructor called."<<a<<endl;
     }
     ~A()
     {  cout<<"Destructor called."<<a<<endl;  }
     void Print()
     {  cout<<a<<endl;  }
 private:
     int a;
 };
 void main()
 {
     A a[4],*p;
     int n=1; 
     p=a;
     for(int i=0;i<4;i++)
         a[i]=A(++n);
     for(i=0;i<4;i++)
          (p+i)->Print();
 }

输出:

 Default constructor called. 0
 Default constructor called. 0
 Default constructor called. 0
 Default constructor called. 0
 Destructor called. 2
 Destructor called. 3
 Destructor called. 4
 Destructor called. 5
 2
 3
 4
 5
  Destructor called. 5
  Destructor called. 4
  Destructor called. 3
  Destructor called. 2

A(++n)创建一个临时对象,该对象在创建后不久就会自动销毁。这说明了第一批析构函数调用。

代码的注释版本:

void main()
{
    A a[4]; // Create 4 A : 4 calls to A().
    A* p;
    int n = 1; 
    p = a;
    for (int i = 0; i < 4; i++) {
        ++n;
        a[i] = A(n); // construct temporary A(n); call A(n), assign it into a[i]
                     // then call ~A();
    }
    for (int i = 0; i < 4; i++)
         (p + i)->Print();
 } // A a[4] goes out of scope and so call ~A() in reverse order.