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

2022-08-16 00:00:00 destructor scope c++

我正在尝试理解退出作用域时析构函数调用的顺序。假设我有以下代码:

class Parent{

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

class Child: public parent{

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

现在,我知道子构造函数和析构函数派生自父函数,因此以下主函数:

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

左边的情况适用于男孩首先被摧毁的情况,右边的情况适用于人首先被摧毁的情况。计算机如何决定首先删除哪一个?


解决方案

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

相关文章