Vector initialization with double curly braces: std :: string vs int

In answer to this question: Initializing vector <string> with double curly braces

shown, that

vector<string> v = {{"a", "b"}};

will call a constructor std::vectorwith initializer_listwith one element . Thus, the first (and only) element in the vector will be built from {"a", "b"}. This leads to undefined behavior, but it does not follow here.

I found that

std::vector<int> v = {{2, 3}};

Constructor call std::vectorwith initializer_listfrom two elements .

Why is the reason for this difference in behavior?

+3
source share
2 answers

: -, std::initializer_list, , , ( [over.match.list]).

a std::initializer_list<E> const E[N] N ( [ dcl.init.list]/5).

vector<string> v = {{"a", "b"}}; initializer_list<string>, 1 const string, string, {"a", "b"}. - string, , ( UB, ). .


vector<int> v = {{2, 3}}; initializer_list<int>, 1 const int, int {2, 3}. .

, vector. :

  • vector(vector&& ), , , {2, 3} - 2 const int, .
  • vector(std::initializer_list<int> ), . , initializer_list {2, 3}, .

, [over.ics.list], vector(vector&& ) , vector(initializer_list<int> ) identity, .


, vector(vector const&) , .

+2

​​ . std::vector c'tor:

vector( std::initializer_list<T> init, 
        const Allocator& alloc = Allocator() );

. {2, 3} std::initializer_list<int> ( ), .

+2

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


All Articles