C++ 构造函数初始化列表求值顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1242830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Constructor initialization-list evaluation order
提问by Matt
I have a constructor that takes some arguments. I had assumed that they were constructed in the order listed, but in one case it appears they were being constructed in reverse resulting in an abort. When I reversed the arguments the program stopped aborting. This is an example of the syntax I'm using. The thing is, a_ needs to be initialized before b_ in this case. Can you guarantee the order of construction?
我有一个带有一些参数的构造函数。我曾假设它们是按照列出的顺序构建的,但在一种情况下,它们似乎是反向构建的,导致中止。当我反转参数时,程序停止中止。这是我正在使用的语法示例。问题是,在这种情况下, a_ 需要在 b_ 之前初始化。你能保证施工顺序吗?
e.g.
例如
class A
{
public:
A(OtherClass o, string x, int y) :
a_(o), b_(a_, x, y) { }
OtherClass a_;
AnotherClass b_;
};
回答by AraK
It depends on the order of member variable declaration in the class. So a_
will be the first one, then b_
will be the second one in your example.
这取决于类中成员变量声明的顺序。所以a_
将是第一个,然后b_
将是您的示例中的第二个。
回答by GManNickG
To quote the standard, for clarification:
引用标准,澄清一下:
12.6.2.5
Initialization shall proceed in the following order:
...
- 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).
...
12.6.2.5
初始化应按以下顺序进行:
...
- 然后,非静态数据成员应按照它们在类定义中声明的顺序进行初始化(同样与 mem 初始化程序的顺序无关)。
...
回答by Adam Getchell
The standard referencefor this now appears to be 12.6.2 section 13.3:
对此的标准参考现在似乎是 12.6.2 第 13.3 节:
(13.3) — Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
(13.3) — 然后,非静态数据成员按照它们在类定义中声明的顺序进行初始化(同样与 mem 初始化程序的顺序无关)。