gpt4 book ai didi

c++ - 为什么在使用大括号初始值设定项列表时首选 std::initializer_list 构造函数?

转载 作者:IT老高 更新时间:2023-10-28 12:47:18 26 4
gpt4 key购买 nike

考虑代码

#include <iostream>

class Foo
{
int val_;
public:
Foo(std::initializer_list<Foo> il)
{
std::cout << "initializer_list ctor" << std::endl;
}
/* explicit */ Foo(int val): val_(val)
{
std::cout << "ctor" << std::endl;
};
};

int main(int argc, char const *argv[])
{
// why is the initializer_list ctor invoked?
Foo foo {10};
}

输出是

ctor
initializer_list ctor

据我了解,值 10 被隐式转换为 Foo (第一个 ctor 输出),然后初始化构造函数启动在(第二个 initializer_list ctor 输出)。我的问题是为什么会这样?标准构造函数 Foo(int) 不是更好的匹配吗?即,我希望这个片段的输出只是 ctor

PS:如果我将构造函数 Foo(int) 标记为 explicit,那么 Foo(int) 是唯一调用的构造函数,如整数 10 现在不能隐式转换为 Foo

最佳答案

§13.3.1.7 [over.match.list]/p1:

When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:

  • Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.
  • If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

If the initializer list has no elements and T has a default constructor, the first phase is omitted. In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed.

只要有一个可行的初始化列表构造函数,当使用列表初始化并且初始化列表至少有一个元素时,它将胜过所有非初始化列表构造函数。

关于c++ - 为什么在使用大括号初始值设定项列表时首选 std::initializer_list 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27144054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com