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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 No you cannot have a object that is a braced-init-list They can only be used to initialize things.
@will here is a good related read: stackoverflow.com/questions/37682392/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.