2

So i can do this:

#include <iostream>
#include <vector>
main(){   
    auto init = {1,2,3};
    std::vector<int> v(init);
}

and i can do this:

#include <iostream>
#include <vector>
main(){   
    int i[3] = {1,2,3};
}

Why can i not do this:

#include <iostream>
#include <vector>
main(){   
    auto init = {1,2,3};
    int i[3] = init;
}

?

the compiler tells me this:

main.cpp: In function 'int main()':
main.cpp:10:16: error: array must be initialized with a brace-enclosed 
initializer
     int i[3] = init;
                ^~~~

exit status 1

it does not make a difference if i create init with std::initializer_list<int> instead of auto.

You can mess around with it here.

will
  • 10,260
  • 6
  • 46
  • 69

1 Answers1

3

When you do auto init = {1,2,3}; you get a std::initialized_list. This is not the same as just {1,2,3} which is a braced-init-list. You can initialize an array with a braced-init-list as it is an aggregate but you cannot use a std::initialized_list as that requires a constructor.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • aah, so `{1,2,3}` is not actually an `std::initializer_list`, but a *braced-init-list*, and there is a constructor that gives me a `std::initializer_list` from that. Can i create an instance of a *braced-init-list*? – will Jul 21 '17 at 15:12
  • @will No you cannot have a object that is a *braced-init-list* They can only be used to initialize things. – NathanOliver Jul 21 '17 at 15:15
  • @will here is a good related read: https://stackoverflow.com/questions/37682392/what-is-a-curly-brace-enclosed-list-if-not-an-intializer-list – NathanOliver Jul 21 '17 at 15:16