Copy initialization in constructor initializer?

Why doesn't my constructor initializer use copy initialization?

struct S { int a; S(int b) : a(b) {} }; // direct initialization compiles struct T { int a; T(int b) : a = b {} }; // copy initialization does not 

I got confused because a(b) and a = b are both expressions (postfix and assigning expressions, respectively), and my C ++ book [1] says that "an initializer can be any arbitrarily complex expression."

[1] Lippman, Lahoya, Mu. "C ++ Primer, 4th ed.". p457.

+1
source share
1 answer

This is not a direct initialization. T a = b; called copying. Direct initialization T a(1, 'foo', false); , and in your constructor you should write the familiar T(int b) : a(b, 'foo', false) { } to achieve this effect, as you did in the first example.

In contrast, T a; called the default initialization, which you achieve by leaving the variable completely unchanged in the list of initializers. Its effect is to call the default constructor for class types and not to initialize the main types at all (for example, for arrays).

Conversely, value initialization can be written as T(int b) : a() { } . You can also use value initialization in new expressions, but they cheat automatic declarations due to annoying parsing.

I think that direct, default, and initialization of values ​​are the only valid forms of initialization in the initialization lists in C ++ 98/03, and C ++ 11 adds different kinds of uniform initialization to the mix.

+3
source

Source: https://habr.com/ru/post/1379571/


All Articles