构造函数初始化列表中的执行顺序 [英] Order of execution in constructor initialization list

查看:685
本文介绍了构造函数初始化列表中的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造函数初始化列表中的执行顺序是否可以确定?我知道一个类中的成员顺序是这些成员将被初始化的顺序,但是如果我有这样的场景:

Is order of execution in constructor initialization list determinable? I know that members order in a class is the order in which those members will be initialized but if I have scenario like this:

class X()
{
X_Implementation* impl_;
};  

and then providing that allocator is available:

X::X():impl_(Allocate(sizeof(X_Implementation)))//HERE I'M ALLOCATING <--1
,impl_(Construct<X_Implementation>(impl_))//AND HERE I'M CONSTRUCTING <--2
{
}

但是为了使这个可靠,这个顺序必须是从左到右。它是保证的伟大的书的std ::或不?

but in order for this to be dependable this order MUST be from left to right. Is it guarantied by GREAT BOOK OF std:: or not? If not I can always move the second line into the body.

推荐答案

根据ISO / IEC 14882:2003 12.6.2:

According to ISO/IEC 14882:2003(E) section 12.6.2:


初始化将按以下顺序进行:

Initialization shall proceed in the following order:


  • 首先,如下所述,只有对于最大派生类的构造函数,虚拟基类才会按照它们出现在深度优先从左到右遍历的方式初始化。基本类的有向无环图
    ,其中从左到右是派生的
    类base-specifier-list中基类名的出现顺序。

  • 然后,直接基类应按声明顺序初始化,因为它们出现在base-specifier-list
    中(不管mem初始化器的顺序如何)。

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


  • 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.
  • 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).
  • Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  • Finally, the body of the constructor is executed.

所以,按照这个顺序,你会有你的订单。还根据标准,订单被规定为使得对象可以以正好相反的顺序被初始化。

So, follow that order, and you'll have your order. Also according to the standard, the order is prescribed as such so that objects can be uninitialized in the precisely reverse order.

这篇关于构造函数初始化列表中的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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