离开范围时析构函数调用的顺序? (C ++)

时间:2014-12-16 03:08:02

标签: c++ scope destructor

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

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";}
};

现在,我知道子构造函数和析构函数是从父类派生的,所以主要是:

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,则应用右侧案例。计算机如何决定首先删除哪一个?

1 个答案:

答案 0 :(得分:4)

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