列表初始化(又名统一初始化)和 initializer_list?

List initialization (aka uniform initialization) and initializer_list?

为什么下面的代码给出不同的输出?

std::vector<int> v{12};
std::cout << v.size() << std::endl;
std::vector<int> v(12);
std::cout << v.size() << std::endl;

如果我列表初始化一个对象,该对象的构造函数接受 initializer_list 作为参数怎么办?

我如何调用 std::vector::vector(size_t) 进行列表初始化?

List-initialization 更喜欢带有 std::initializer_list 参数的构造函数。来自 cppreference:

The effects of list-initialization of an object of type T are:

[...cases that do not apply here ...]

  • 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).

虽然直接初始化不喜欢 initializer_list 构造函数。它调用以大小为参数的构造函数。

来自 https://en.cppreference.com/w/cpp/container/vector/vector

Note that the presence of list-initializing constructor (10) means list initialization and direct initialization do different things:

std::vector<int> b{3}; // creates a 1-element vector holding {3}
std::vector<int> a(3); // creates a 3-element vector holding {0, 0, 0}
std::vector<int> d{1, 2}; // creates a 2-element vector holding {1, 2}
std::vector<int> c(1, 2); // creates a 1-element vector holding {2}

And how can I call std::vector::vector(size_t) with list-initialization?

如上所述,std::initializer_list 构造函数的存在阻止您通过 list-initialization.

调用另一个构造函数