Search code examples
c++c++11constructorinitializer-list

C++11 initializer list length is not checked in implicit constructor


I've found that when a simple data struct with default constructors contains an array, the default constructor can be called with a different number of arguments, ie:

struct LayerData
{
    uint32_t d[60];
};

Can be initialized by:

LayerData in({rand(),rand(),rand(),rand(),rand()});

And it compiles properly.

Is this the expected behaviour in C++11? Is there no compile-time checking of sizes in the implicit constructor?


Solution

  • N3337 8.5.1/7

    If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from an empty initializer list (8.5.4).

    struct S { int a; const char* b; int c; };
    S ss = { 1, "asdf" };
    

    initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0.

    So in your example first 5 elements are initialized with rand() other with int() which is 0.