成员构造函数和析构函数调用的顺序 [英] Order of member constructor and destructor calls

查看:387
本文介绍了成员构造函数和析构函数调用的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哦C ++大师,我寻求你的智慧。告诉我,如果C ++保证下面的程序,告诉我:

Oh C++ gurus, I seek thy wisdom. Speak standardese to me and tell my if C++ guarantees that the following program:

#include <iostream>
using namespace std;

struct A
{
    A() { cout << "A::A" << endl; }
    ~A() { cout << "A::~" << endl; }
};

struct B
{
    B() { cout << "B::B" << endl; }
    ~B() { cout << "B::~" << endl; }
};

struct C
{
    C() { cout << "C::C" << endl; }
    ~C() { cout << "C::~" << endl; }
};

struct Aggregate
{
    A a;
    B b;
    C c;
};

int main()
{
    Aggregate a;
    return 0;
}

将始终产生

A::A
B::B
C::C
C::~
B::~
A::~

换句话说,是保证按声明顺序初始化并以相反的顺序?

In other words, are members guaranteed to be initialized by order of declaration and destroyed in reverse order?

推荐答案


换句话说,是保证按声明顺序并以相反的顺序销毁?

In other words, are members guaranteed to be initialized by order of declaration and destroyed in reverse order?

请参阅12.6.2


6 初始化将在
中按照以下顺序进行:

6 Initialization shall proceed in the following order:


  • 首先,如下所述,只有
    是最导出的
    类的构造函数,virtual base
    类应以
    顺序初始化,它们出现在深度优先
    从左到右遍历
    基本
    类的有向无环图,其中left- to-right是派生类
    base-specifier-list中基类
    名称的
    出现顺序。

  • First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where "left-to-right" is the order of appearance of the base class names in the derived class base-specifier-list.

然后,直接
基类必须在
声明顺序中初始化,因为它们出现在
base-specifier-列表(不管
是mem初始化器的顺序)。

Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

然后,非静态数据成员将
按照它们的顺序初始化
在类定义中声明
(再次不考虑
mem初始化器的顺序)。

Then, non-static data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

最后,执行构造函数
body的
复合语句。 [注:
声明命令强制为
,确保base和成员子对象
以与
初始化相反的顺序被销毁。 - end note]

Finally, the compound-statement of the constructor body is executed. [ Note: the declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —end note ]

这篇关于成员构造函数和析构函数调用的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆