gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:21:11 25 4
gpt4 key购买 nike

我的 friend 告诉我

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>吗?

最佳答案

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

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.



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

关于c++ - 为什么C++ 11不允许使用auto进行直接列表初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60088003/

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