为什么 C++20 不支持乱序指定初始化器?

Why C++20 doesn't support out-of-order designated initializer?

在阅读C++ reference时,我对这一段有疑问:

Note: out-of-order designated initialization, nested designated initialization, mixing of designated initializers and regular initializers, and designated initialization of arrays are all supported in the C programming language, but are not allowed in C++.

是否有任何技术原因阻止 C++ 支持乱序指定初始化?

是的,附件 C 中涵盖了基本原理(信息性) 兼容性特别是[diff.dcl]p10强调我的):

Affected subclause: [dcl.init.aggr] Change: In C++, designated initialization support is restricted compared to the corresponding functionality in C. In C++, designators for non-static data members must be specified in declaration order, designators for array elements and nested designators are not supported, and designated and non-designated initializers cannot be mixed in the same initializer list. Example:

struct A { int x, y; };
struct B { struct A a; };
struct A a = {.y = 1, .x = 2};  // valid C, invalid C++
int arr[3] = {[1] = 5};         // valid C, invalid C++
struct B b = {.a.x = 0};        // valid C, invalid C++
struct A c = {.x = 1, 2};       // valid C, invalid C++

Rationale: In C++, members are destroyed in reverse construction order and the elements of an initializer list are evaluated in lexical order, so field initializers must be specified in order. Array designators conflict with lambda-expression syntax. Nested designators are seldom used.

first revision of the proposal也讨论了这个话题:

To meet these expectations for guaranteed copy elision, we require the designators to appear as a subsequence of the data member declaration sequence, so that the evaluation order matches the declaration order, and it is also textually left­to­right in designated initialization

您可以获得最新版本here

只有一小部分来自 C 的指定初始化选项是痛苦的。也许将来会得到纠正。目前,一些编译器比 C++20 标准要宽松一些。此代码段:

struct A {int x, y;};
A a = {.y=2, .x=4};

编译时出现警告,并且在 clang-10.0.0 和更新版本(参见 https://godbolt.org/z/Ybnzz5chx)下运行良好。