【问题标题】:How Destructor executes?析构函数如何执行?
【发布时间】:2017-12-01 14:21:34
【问题描述】:

我在 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

【问题讨论】:

    标签: c++ arrays oop destructor new-operator


    【解决方案1】:

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

    即当你分配数组时,new[] 在一个方向构造对象,然后当你调用delete[] 时,对象从数组的末尾被销毁。

    有关此行为,请参阅 @StoryTeller's answer for a quote from the C++ standard

    【讨论】:

    • 如果我写delete p而不是delete []p会发生什么,所以多次调用Destructor
    • @AmanWarudkar 请参阅stackoverflow.com/questions/6953457/…,您应该始终删除使用new[]delete[] 分配的数组
    【解决方案2】:

    我不知道为什么输出不像我想的那样。

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

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

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

    阅读更多Why destructors are not called in reverse order for array of objects?


    如果我写 delete p 而不是 delete []p,会发生多少次 Destructor 被调用?

    C++ 要求您使用delete[] 删除数组并使用delete 删除非数组。所以我无法回答这个问题。阅读更多Delete and delete [] are the same when deleting arrays?

    【讨论】:

    • 如果我写delete p而不是delete []p会发生什么,所以多次调用Destructor
    • @AmanWarudkar 更新了我的答案,希望对您有所帮助!不要忘记接受答案。好奇地感谢您的链接和很好的答案顺便说一句。
    【解决方案3】:

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

    [expr.delete/6]

    如果删除表达式的操作数的值不为空 指针值,删除表达式将调用析构函数(如果 any) 用于被删除的对象或数组的元素。 在 数组的情况下,元素将按顺序销毁 递减地址(即按完成的相反顺序 它们的构造函数; 参见 [class.base.init])。

    【讨论】:

    • 按标准报价击败我!
    猜你喜欢
    • 2015-08-02
    • 2017-02-13
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 2016-11-15
    • 2016-04-20
    相关资源
    最近更新 更多