Search code examples
arraysc++11implicitinitializer-list

Does C++11's unified initialize contains an implicit type conversion to array?


auto buf={1,2,3}

here the type of "buf" is std::initializer_list, but

int buf[]={1,2,3};

The left side expression is a declaration of variable "buf",type int[], on the right side is a std::initializer_list

So is there an implicit type conversion here, from std::initializer_list to int[]? Or new STL defines such a conversion?

How can I prove if there's or there's not such a conversion here?


Solution

  • In the case of auto buf = {1, 2, 3}; the compiler has to deduce what type buf is and picks std::initializer_list<int>.

    However in the case of int buf[] = {1, 2, 3};, it knows the type of buf and the only way to initialize it is through aggregate initialization. Also notice that the size is not specified and is deduced by the number of elements provided. This is unique to arrays.

    There is no conversion available here. If you try to force a construction from a std::initializer_list<int> you get a compilation error:

    main.cpp:8:9: error: array initializer must be an initializer list
        int buf[] = std::initializer_list<int>({1, 3, 4});
            ^