Does C ++ initialization repeat 11 initialized fields of an element?

C ++ 11 now supports setting the value of a member field of a class during declaration, for example:

class MyClass { private int test = 0; } 

If I also initialize the variable in the constructor as follows:

 class MyClass { private int test = 0; public: MyClass() : test(1) { } } 

will this cause the variable to have a value set twice, or does the specification indicate that the compiler should optimize this to initialize the variable only once? If the specification dictates nothing, do you know the behavior of well-known compilers (e.g. MSVC, GCC, etc.) regarding this?

+7
c ++ c ++ 11
source share
1 answer

The standard actually has a rule for this, in ยง12.6.2 / 9:

If the specified non-static data member has either a parenthesis initializer or equal, or a mem initializer, the initialization indicated by the mem initializer is executed, and non-static data elements of the parenthesis or equal -initializer are ignored. [Example: given

 struct A { int i = /โˆ— some integer expression with side effects โˆ—/ ; A(int arg) : i(arg) { } // ... }; 

the constructor A (int) will simply initialize me to the arg value, and side effects in the format brace-or-equal- the initializer will not take place. - end of example]

So, in the described case, if the default constructor is called, only initialization will be performed, and test will be 1 .

+14
source share

All Articles