为什么 C++11 不允许使用自动进行直接列表初始化

Why doesn't c++11 allow direct-list-initialization with auto

我朋友告诉我的

auto x1 = {3}; // x1 is std::initializer_list<int>
auto x2{1, 2}; // error: not a single element
auto x3{3};    // x3 is int

不太明白为什么auto x2{1, 2};不合法,难道不能直接推导为std::initializer_list<int>吗?

根据我的编译器,这是因为 x2 是一个标量,因此只能有一个索引。然而,下面的编译是因为它是一个数组并且数组有两个索引。

自动 x2[]{1,2};

标准有意限制了这种情况。

auto x2{1, 2}; // error: not a single element

Auto and braced initializers cause a teachability problem; we want to teach people to use uniform initialization, but we need to specifically tell programmers to avoid braces with auto. In C++14, we now have more cases where auto and braces are problematic; return type deduction for functions partially avoids the problem, since returning a braced-list won't work as it's not an expression. However, returning an auto variable initialized from a braced initializer still returns an initializer_list, inviting undefined behaviour. Lambda init captures have the same problem. This paper proposes to change a brace-initialized auto to not deduce to an initializer list, and to ban brace-initialized auto for cases where the braced-initializer has more than one element.

有关详细信息,请参阅 ISO/IEC JTC1/SC22/WG21 C++ 标准委员会关于 Auto and braced-init-lists 的文件。