skip to content

Why does std::vector<int> v{10, 20} hold two elements in C++ while std::vector<int> v(10, 20) holds ten?

level: middleimportance: must knowfreq 70%

answer

  1. two rounds of overload resolution
  2. initializer-list constructors go first
  3. parentheses never consider the list
  4. empty braces call the default constructor
  5. no viable list constructor: fall back

basics

~10 s

Braces make overload resolution try initializer-list constructors first. vector<int>{10, 20} matches vector(initializer_list<int>) and stores 10 and 20, while vector<int>(10, 20) calls the count-and-value constructor and stores ten copies of 20.

solid answer

~40 s

List-initialization of a class runs overload resolution in **two phases**. If the braced list is non-empty, or the class has no default constructor, only the **initializer-list constructors** are tried first, with the whole list as one `std::initializer_list` argument; only if none is viable are all constructors tried with the elements as separate arguments. `std::vector<int>` has `vector(initializer_list<int>)`, so `{10, 20}` means "the elements 10 and 20", and `{10}` means one element. Parentheses never consider the list form, so `(10, 20)` picks `vector(size_type, const int&)`: ten copies of 20. Empty braces are special: `std::vector<int>{}` value-initializes with the default constructor. When no list constructor fits — `std::vector<std::string>{3}`, where 3 cannot become a `std::string` — phase two runs and you get three empty strings.

code

cpp · 14 lines
cpp
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<int> a(10, 20);   // ten elements, each 20
    std::vector<int> b{10, 20};   // two elements: 10 and 20
    std::vector<int> c(10);       // ten zeros
    std::vector<int> d{10};       // one element: 10
    std::vector<int> e{};         // empty: default constructor
    std::vector<std::string> f{3};   // no list constructor fits: three empty strings
    std::cout << a.size() << ' ' << b.size() << ' ' << c.size() << ' '
              << d.size() << ' ' << e.size() << ' ' << f.size() << '\n';
}

go deeper

for a junior

Remember that braces on a vector list the elements, while parentheses pass a count and a value.

for a middle

Explain the two-phase overload resolution, the empty-braces rule and why vector<string>{3} falls back to the count constructor.

for a senior

Recognise when adding an initializer_list constructor breaks callers, and choose braces or parentheses deliberately in generic factories.

for a principal

Weigh a uniform-braces style against the initializer-list hazard when setting the initialization conventions for a codebase.

## Two rounds of overload resolution When a braced list initializes an object of a non-aggregate class type, overload resolution selects the constructor in **two phases**: 1. If the list is not empty, or the class has no default constructor, the candidates are only the **initializer-list constructors** — constructors whose first parameter is `std::initializer_list<E>` (or a reference to one) and whose other parameters have defaults. The entire braced list is the single argument. 2. Only if phase one finds no viable constructor are **all** constructors considered, with the list's elements as separate arguments. An empty list is handled before either phase: if the class has a default constructor, `T{}` value-initializes the object, so `std::vector<int>{}` calls the default constructor, not `vector(initializer_list<int>)` with an empty list. ## The vector cases side by side | Expression | Constructor chosen | Contents | |---|---|---| | `std::vector<int> v(10, 20);` | `vector(size_type, const int&)` | ten elements, each 20 | | `std::vector<int> v{10, 20};` | `vector(initializer_list<int>)` | 10, 20 | | `std::vector<int> v(10);` | `vector(size_type)` | ten zeros | | `std::vector<int> v{10};` | `vector(initializer_list<int>)` | one element: 10 | | `std::vector<int> v{};` | default constructor | empty | | `std::vector<std::string> v{3};` | `vector(size_type)` after phase one fails | three empty strings | The last row is the fallback in action: phase one needs `3` to convert to `std::string`, which it cannot, so no initializer-list constructor is viable and phase two picks the count constructor. The same braces therefore mean "elements" for `std::vector<int>` and "count" for `std::vector<std::string>` — a frequent source of confusion in generic code. ## Phase one wins even when it is worse Phase one does not compete with the other constructors; it **pre-empts** them. If an initializer-list constructor is viable, it is chosen even when another constructor would be an exact match and the list constructor needs conversions. And narrowing does not make it non-viable: `std::vector<int> v{10, 20.5};` selects `vector(initializer_list<int>)` and is then ill-formed because `20.5` narrows — the compiler does not fall back to `vector(size_type, const int&)`. ## Consequences for your own classes - **Adding an initializer-list constructor changes existing call sites.** If a `Palette` type once had `Palette(int count, Color fill)` and you later add `Palette(std::initializer_list<Color>)`, every `Palette{4, red}` whose arguments convert to `Color` silently changes meaning. Treat adding one as an API break. - **Generic code must choose deliberately.** A factory that writes `T{std::forward<Args>(args)...}` behaves differently from one that writes `T(std::forward<Args>(args)...)` for any `T` with a list constructor. The standard library's `std::make_unique` and `emplace_back` use parentheses for this reason. - **Copying from a single braced element** of the same class type can also be captured by a list constructor whose element type is constructible from the class, which is why the standard's example `S s3{s2};` invokes `S(std::initializer_list<S>)`, not the copy constructor. ## Aggregates follow different rules Everything above is about classes with constructors. For an **aggregate** — a struct with public members and no user-declared constructors, or `std::array` — braces perform aggregate initialization instead: each element initializes the next member in order, there is no constructor overload resolution and no initializer-list preference. `std::array<int, 3> a{1, 2, 3};` works through **brace elision**: `std::array` wraps a built-in array member, and the inner braces may be omitted. `std::array<int, 3> b = {1};` sets the first element and zero-initializes the rest. So `{10, 20}` means elements for both `std::vector<int>` and `std::array<int, 2>`, but for entirely different reasons, and `std::array` has no count constructor to fall back to. ## Rules of thumb - Use parentheses when you mean "call this constructor with these arguments" on a container or any type with a list constructor. - Use braces when you mean "these are the elements", or for aggregates and scalars where you want the narrowing check. - Read `T{x}` on an unfamiliar type as "does `T` have an initializer-list constructor?" before reading it as a constructor call.

  • Why is std::vector<int> v{10, 20.5}; a compile error instead of ten copies of 20?
    Phase one selects `vector(initializer_list<int>)` because it is viable; the narrowing of `20.5` to `int` does not remove it from consideration. Once chosen, the narrowing conversion makes the initialization ill-formed. The compiler never reaches phase two, so the count-and-value constructor is not an alternative.
  • Why do std::make_unique and emplace_back construct with parentheses rather than braces?
    With braces, any element type that has an initializer-list constructor would have its arguments reinterpreted as a list of elements, so `make_unique<std::vector<int>>(10, 20)` would build two elements instead of ten. Parentheses call the constructor the caller named. C++20's parenthesized aggregate initialization lets these functions build aggregates too.

  • v{10, 20} and v(10, 20) call the same constructor
  • the compiler picks the best match among all constructors for braces
  • empty braces call the initializer_list constructor with no elements
  • braces always mean elements for any std::vector
  • adding an initializer_list constructor never affects existing callers