gpt4 book ai didi

c++ - C++ 20从带括号的值列表初始化聚合,不支持内部数组

转载 作者:行者123 更新时间:2023-12-02 09:53:51 25 4
gpt4 key购买 nike

C++ 20采用了p0960-允许从带括号的值列表中初始化聚合。

确切的措辞([dcl.init] 17.6.2.2)说:

[...] if no constructor is viable, the destination type is an aggregate class, and the initializer is a parenthesized expression-list, the object is initialized as follows.

Let e1 , …, en be the elements of the aggregate ([dcl.init.aggr]).

Let x1, …, xk be the elements of the expression-list.

If k is greater than n, the program is ill-formed.

The element ei is copy-initialized with xi for 1 ≤ i ≤ k . The remaining elements are initialized with their default member initializers [...]



这不允许使用带括号的值列表初始化内部数组:
struct Foo {
int i, j;
};

struct Moo {
int arr[2];
};

int main() {
// before C++20:
Foo foo1{1, 2};
// with C++20:
Foo foo2(1, 2); // p0960! we are good

// before C++20:
Moo moo1{1, 2};
// C++20 - oops p0960 doesn't help here:
Moo moo2(1, 2); // error: too many initializers

// before C++20:
std::array<int, 2> arr1{1, 2}; // OK
std::array<int, 2> arr2({1, 2}); // OK
std::array<int, 2> arr3{{1, 2}}; // OK
// C++20 - oops p0960 doesn't help here:
std::array<int, 2> arr4(1, 2); // error: too many initializers
}

不能使用圆括号将 std::array初始化这一事实使它无法参与从值列表中创建未知类型 T的对象的通用代码中(例如,使用 make_sharedmake_uniquemake_from_tuple等的算法)。

为什么p0960没有采取更简单的方法使 ()初始化更像 {}

例如,类似:

if no constructor is viable, the destination type is an aggregate class, and the initializer is a parenthesized expression-list, the object would be initialized as if the values were sent with brace-initialization.

最佳答案

p0960在r1和r2之间改变:

r2: This revision changes the mental model from the original “literal rewrite to a braced list” to “as if a synthesized, explicit constructor with appropriate mem-initializers was called 1. This has the effect of allowing narrowing conversions in the parenthesized list, even when narrowing conversions would be forbidden in the corresponding braced list syntax. It also clarifies the non-extension of temporary lifetimes of temporaries bound to references, the absence of brace elision, and the absence of a well-defined order of evaluation of the arguments.


可以在更改的p0960设计原理中找到进行此更改的原因:

r1: Parenthesized initialization and braced-initialization should be as similar as possible.

r2:Parenthesized initialization and braced-initialization should be as similar as possible, but as distinct as necessary to conform with the existing mental models of braced lists and parenthesized lists.(emphasis mine)


“为什么p0960没有采用更简单的方法使()初始化更像{}?”:
当决定采用现有的心理模型 1 时,不允许括号删除似乎是唯一的方法。

关于c++ - C++ 20从带括号的值列表初始化聚合,不支持内部数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62041402/

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