问题描述
在此问题的答案中:
它显示为
vector<string> v = {{"a", "b"}};
将调用 std :: vector
构造函数使用一个元素的 initializer_list
。因此,向量中的第一个(也是唯一一个)元素将由 { a, b}
构造。这会导致不确定的行为,但这超出了这里的重点。
will call the std::vector
constructor with an initializer_list
with one element. So the first (and only) element in the vector will be constructed from {"a", "b"}
. This leads to undefined behavior, but that is beyond the point here.
我发现的是
std::vector<int> v = {{2, 3}};
将调用 std :: vector
构造函数两个元素的初始化程序列表
。
为什么这种行为方式不同的原因?
Why is the reason for this difference in behavior?
推荐答案
类类型的列表初始化的规则基本上是:首先,仅考虑进行重载解析std :: initializer_list
构造函数,然后,如有必要,对所有构造函数进行重载解析(这是)。
The rules for list initialization of class types are basically: first, do overload resolution only considering std::initializer_list
constructors and then, if necessary, do overload resolution on all the constructors (this is [over.match.list]).
初始化 std :: initializer_list<时; E>
从初始化列表中,就好像我们从 N 元素中实现了 const E [N]
在初始化列表中(来自,其中 vector(vector&&)
构造函数是,但 vector(initializer_list< int>)
构造函数为,因此是首选。
To pick which constructor, we have to go to into [over.ics.list], where the vector(vector&& )
constructor is a user-defined conversion sequence but the vector(initializer_list<int> )
constructor is identity, so it's preferred.
为了完整起见, vector(vector const&)
为也是可行的,但是出于其他原因,我们宁愿将move构造函数比于copy构造函数。
For completeness, vector(vector const&)
is also viable, but we'd prefer the move constructor to the copy constructor for other reasons.
这篇关于带双花括号的向量初始化:std :: string vs int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!