Copy initialization in constructor initializer?

后端 未结 1 532
无人及你
无人及你 2021-01-16 11:52

Why can\'t my constructor initializer use copy initialization?

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


        
相关标签:
1条回答
  • 2021-01-16 12:19

    That's not direct initialization. T a = b; is called copy intialization. Direct initialization is T a(1, 'foo', false);, and in your constructor you would write the familiar T(int b) : a(b, 'foo', false) { } to achieve this effect, as you already have in your first example.

    By contrast, T a; is called default initialization, which you achieve by leaving a variable entirely unmentioned in the initializer list. Its effect is to call the default constructor on class types, and to perform no initialization at all on fundamental types (ditto for arrays).

    By contrast again, value initialization can be written as T(int b) : a() { }. You can also use value-initialization in new expressions, but they're tricker in automatic declarations due to the vexing parse.

    I think direct, default and value initialization are the only permissible forms of initialization in initializer lists in C++98/03, while C++11 adds various flavours of uniform initialization to the mix.

    0 讨论(0)
提交回复
热议问题