Fields for participants, construction procedure

In C ++, when you do something like what you see below, is the build order guaranteed?

Logger::Logger() : kFilePath_("../logs/runtime.log"), logFile_(kFilePath_) { // ... } 
+7
source share
2 answers

Yes, the construction procedure is always guaranteed. However, this does not guarantee the same as the order in which objects appear in the initializer list.

Members of variables are constructed in the order in which they are declared in the body of the class. For example:

 struct A { }; struct B { }; struct S { A a; B b; S() : b(), a() { } }; 
First built

a , then b . The order in which member variables appear in the list of initializers does not matter.

+26
source

The build order is the order of the declaration in the class definition.

If the order in ctor-initializer is different, this does not affect the build order. Your compiler may warn you about this.

See 12.6.2 / 5 (2003 edition, named [class.base.init] ):

non-static data members must be initialized in the order in which they were declared in the class definition (again, regardless of the order of the MEM initializers).

+9
source

All Articles