基类初始化器和成员变量初始化器的顺序是否重要? [英] Does the order of base-class initializers and member variable initializers matter?
问题描述
类构造函数的初始化器的顺序是否很重要?
所以说我有:
class MyClass:BaseClass
{
int a,b,c;
public:
MyClass(int);
}
1:
MyClass :: MyClass(int forBase):
a(7),
b(14),
c(28),
BaseClass(forBase){}
eg 2:
MyClass :: MyClass(int forBase):
BaseClass(forBase),
a(7),
b(14),
c(28){}
否。初始化顺序由标准决定,而不是由写初始化的顺序决定:
[C + +11:12.6.2 / 10]:
在非委托构造函数中,初始化
按以下顺序进行:
- 首先,只有对于大多数派生类(1.8)的构造函数,虚拟基类才会按照它们在深度优先从左到右遍历的有向无环图基类,其中从左到右是派生类base-specifier-list中基类的出现顺序。
- 成员按照它们在类定义中声明的顺序(同样不考虑mem初始化器的顺序)来初始化。
- 最后,构造函数的复合语句
事实上,如果你以任何其他顺序写它们,另一个您可能会收到警告:
struct T {
std :: vector< int> v;
int w;
T(int w):w(w),v(0,w){}
};
int main(){
T t(3);
}
// g ++ 4.1.2:
// t.cpp:在构造函数'T :: T(int)'中:
//第3行:warning:'T :: w'将在
之后初始化//第2行:warning:'__gnu_debug_def :: vector< int,std :: allocator< int> > T :: v'
//第5行:警告:在此处初始化
Is the order of the initializers for a class' constructor significant?
So say I have:
class MyClass : BaseClass
{
int a, b, c;
public:
MyClass(int);
}
e.g. 1:
MyClass::MyClass(int forBase) :
a(7),
b(14),
c(28),
BaseClass(forBase) { }
e.g. 2:
MyClass::MyClass(int forBase) :
BaseClass(forBase),
a(7),
b(14),
c(28) { }
Would example 1 do something different to example 2?
Would example 1 do something different to example 2?
No. Initialisation order is dictated by the standard, not by the order in which you write the initialisers:
[C++11: 12.6.2/10]:
In a non-delegating constructor, initialization proceeds in the following order:
- First, and only for the constructor of the most derived class (1.8), virtual base classes are 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 classes in the derived class base-specifier-list.
- Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
- 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).
- Finally, the compound-statement of the constructor body is executed.
In fact, if you write them in any other order and one depends on the other, you may well be warned about it:
struct T {
std::vector<int> v;
int w;
T(int w) : w(w), v(0, w) {}
};
int main() {
T t(3);
}
// g++ 4.1.2:
// t.cpp: In constructor 'T::T(int)':
// Line 3: warning: 'T::w' will be initialized after
// Line 2: warning: '__gnu_debug_def::vector<int, std::allocator<int> > T::v'
// Line 5: warning: when initialized here
这篇关于基类初始化器和成员变量初始化器的顺序是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!