【问题标题】:Order of Destructor Calling When Leaving Scope? (C++)离开范围时的析构函数调用顺序? (C++)
【发布时间】:2014-12-16 03:08:01
【问题描述】:

我试图了解退出范围时析构函数调用的顺序。假设我有以下代码:

class Parent{

Parent(){cout<<"parent c called \n";}
~Parent(){cout<< "parent d called \n";}
};

class Child: public parent{

Child(){cout<< "child c called \n";}
~Child(){cout<<"child d called\n";}
};

现在,我知道子构造函数和析构函数都是从父级派生的,所以下面的main:

int main(){

Parent Man;
Child Boy;

return 0;
}

会产生输出:

parent c called
parent c called
child c called
... //Now what?

但是现在,当我退出范围时会发生什么?我有很多东西需要销毁,那么编译器如何选择顺序?我可以有两种输出可能性:

parent c called           |         parent c called      
parent c called           |         parent c called
child c called            |         child c called
child d called            |         parent d called
parent d called           |         child d called
parent d called           |         parent d called

如果 Boy 首先被破坏,则适用左侧案例,如果 Man 首先被破坏,则适用右侧案例。计算机如何决定先删除哪个?

【问题讨论】:

  • 自动对象、临时对象和成员的析构函数调用顺序与构造函数调用顺序相反。
  • 总是可以运行程序找出来
  • @EdHeal,这将证明什么都没有。样本可能会伪造陈述,但永远无法证明。
  • 安德烈,谢谢,这正是我需要知道的。 Ed,我确实运行了该程序,结果与 Andrey 的描述一致,但我不知道执行它的规则是什么,或者它是否适用于所有情况。因此,尽管我确实知道这个简单示例的输出,但我认为这将是解决我的问题的最直接的方法。
  • 供参考,C++11 标准,第 6.6 节,第 2 段:On exit from a scope (however accomplished), objects with automatic storage duration (3.7.3) that have been constructed in that scope are destroyed in the reverse order of their construction.

标签: c++ scope destructor


【解决方案1】:

在祖先析构函数之前调用派生析构函数。所以Child 析构函数体将首先被调用,然后是Parent 析构函数体。并且构造的对象会以相反的顺序被销毁,所以Boy对象会在Man对象被销毁之前被销毁。

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2012-09-26
    • 1970-01-01
    • 2013-06-24
    相关资源
    最近更新 更多