0

Consider the following program, defining a std::vector containing the value 13:

std::vector<int> vec{13};

This could also have been interpreted as a call to the constructor that initializes the vector with 13 zeros. My question is: how does the compiler choose between constructing a std::vector with an initializer_list or by initializing the vector with 13 zeros?

Jasper Koning
  • 143
  • 1
  • 9
  • 1
    https://stackoverflow.com/questions/9723164/why-does-stdvectorint-b2-create-a-1-element-vector-and-not-a-2-element – Mat Mar 02 '20 at 10:10

1 Answers1

3

Because the construtor taking std::initializer_list is preferred in list initialization.

Otherwise, the constructors of T are considered, in two phases:

  • All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_list

  • If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405