C++隐式拷贝构造函数成员变量拷贝顺序
C++ implicit copy constructor member variable copy ordering
只是想仔细检查一下:C++ 标准保证成员变量按照 隐式 复制构造函数的声明顺序进行复制,对吗?在下面的示例中,a
在 b
之前被复制,对吗? (假设 A
和 B
都有非平凡的复制构造函数,并且 a
在 b
被复制之前被复制对于正确性很重要。)
struct Foo {
A a;
B b;
};
我想知道它是否由标准保证或是否依赖于实现?
是的,保证implicitly-defined copy constructor的初始化顺序:
For non-union class types (class and struct), the constructor performs
full member-wise copy of the object's bases and non-static members, in
their initialization order, using direct initialization.
而data members的初始化顺序就是他们声明的顺序
3) Then, non-static data members are initialized in order of declaration in the class definition.
根据标准,[class.copy.ctor]/14
(强调我的)
The implicitly-defined copy/move constructor for a non-union class X
performs a memberwise copy/move of its bases and members. [ Note:
Default member initializers of non-static data members are ignored.
See also the example in [class.base.init]. — end note ] The order of
initialization is the same as the order of initialization of bases and
members in a user-defined constructor (see [class.base.init]).
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).
只是想仔细检查一下:C++ 标准保证成员变量按照 隐式 复制构造函数的声明顺序进行复制,对吗?在下面的示例中,a
在 b
之前被复制,对吗? (假设 A
和 B
都有非平凡的复制构造函数,并且 a
在 b
被复制之前被复制对于正确性很重要。)
struct Foo {
A a;
B b;
};
我想知道它是否由标准保证或是否依赖于实现?
是的,保证implicitly-defined copy constructor的初始化顺序:
For non-union class types (class and struct), the constructor performs full member-wise copy of the object's bases and non-static members, in their initialization order, using direct initialization.
而data members的初始化顺序就是他们声明的顺序
3) Then, non-static data members are initialized in order of declaration in the class definition.
根据标准,[class.copy.ctor]/14
(强调我的)
The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members. [ Note: Default member initializers of non-static data members are ignored. See also the example in [class.base.init]. — end note ] The order of initialization is the same as the order of initialization of bases and members in a user-defined constructor (see [class.base.init]).
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).