C ++: flat list of initializers for nested structure?

Defining

struct A {
  int a,b;
};

struct B {
  A a;
  int b;
};

the following initializations are obvious:

B b1 = { { 1 } };    // initializes b1.a.a
B b2 = { { 1, 2 } }; // initializes b1.a.a, b1.a.b
B b3 = { { 1 }, 2 }; // initializes b1.a.a, b1.b

But I am surprised that VC ++ 2013 also allows these initializations without warning:

B b4 = { 1 };       // initializes b4.a.a
B b5 = { 1, 2 };    // initializes b5.a.a, b5.a.b
B b6 = { 1, 2, 3 }; // initializes b6.a.a, b6.a.b, b6.b

Are initializer lists for nested structures / classes standard C ++?

+4
source share
2 answers

Yes, this is standard C ++. With aggregate initialization (and only in aggregate initialization, and not in other forms of list initialization), parentheses can be eliminated, effectively smoothing the aggregate containment hierarchy.

+3
source

Yes, this is standard C ++, which is described in 8.5 initializers.

.

n4296, 8.5.1.12 :

. , -, , ; , initializer-clauses, . , , , - , ; , , .

8.5.1.13:

struct A {
    int i;
    operator int();
};

struct B {
    A a1, a2;
    int z;
};

A a;
B b = { 4, a, a };

a1 4, a2 a z int() a.

+1

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


All Articles