简体   繁体   中英

C++ implicit copy constructor member variable copy ordering

Just want to double check: the C++ standard guarantees that member variables are copied in order of declaration by the implicit copy constructor, right? In the following example, a gets copied before b , right? (Assume that both A and B have non-trivial copy constructors and it's important for correctness that a gets copied before b gets copied.)

struct Foo {
  A a;
  B b;
};

I'm interested if it's guaranteed by the standard or is it implementation dependent?

Yes, the initialization order is guaranteed for 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.

And the initialization order of data members is the order of their declaration.

3) Then, non-static data members are initialized in order of declaration in the class definition.

From the standard, [class.copy.ctor]/14

(emphasis mine)

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] ).

and [class.base.init]/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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM