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

标签 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 首先被摧毁,则适用右侧情况。计算机如何决定先删除哪一个?

最佳答案

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

关于c++ - 离开范围时析构函数调用的顺序? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27496895/

相关文章:

c++ - Boost 1_65_1 不使用 OpenSSL 1.1.0g "undefined reference"编译,但使用 "nm"找到

c++ - 默认构造函数中的歧义

C++ 数组作用域

当在函数内的 if 语句的条件中使用全局变量时,Python 抛出 UnboundLocalError

c++ - 在堆栈展开时使用 RAII 是否安全?

PHP 类析构函数中的 mysql_query(无法建立到服务器的链接)

c++ - 如何使用 composite_key 为 multi_index_container 编写自定义谓词?

c++ - 实现程序配置设置的好方法是什么?

ruby-on-rails - rails : Scope: making a method available to all Views and Controllers

c++ - 析构函数 vs 成员函数竞赛