简体   繁体   English

C ++中的空嵌套初始化器列表

[英]Empty nested initializer list in C++

Consider this piece of code: 考虑这段代码:

struct S {
    float b;
    int a;    
};

int main() {
    S s{{{}}};
    return s.a;
}

Godbolt 哥德宝

Clang 6.0.0 compiles this code, but shows a warning: Clang 6.0.0编译此代码,但显示警告:

<source> warning: too many braces around scalar initializer [-Wmany-braces-around-scalar-init] <source>警告:标量初始化程序周围的括号过多[-Wmany-braces-around-scalar-init]

GCC 8.2 doesn't compile this code and reports an error: GCC 8.2无法编译此代码并报告错误:

<source>: In function 'int main()': <source>:9:10: error: braces around scalar initializer for type 'float' <source>:在函数'int main()'中:<source>:9:10:错误:在类型'float'的标量初始化程序中花括号

Which one is correct? 哪一个是正确的? What does the specification say about this? 规范对此有何说明?

Both compilers are correct. 两种编译器都是正确的。 Unless you violate a rule that says no diagnostic required the compiler should issue you a message. 除非您违反没有诊断要求的规则,否则编译器应向您发送一条消息。 Whether that message is a warning or an error is up to the implementation. 该消息是警告还是错误取决于实现。 Normally you'll get a warning if it is something the compiler can still proceed with and an error when there is no way the compiler can continue. 通常,如果编译器仍然可以继续执行此操作,则会收到警告,如果编译器无法继续运行,则会出现错误。

What does the specification say about this? 规范对此有何说明?

dcl.init.aggr/3 : dcl.init.aggr / 3

3 When an aggregate is initialized by an initializer list as specified in [dcl.init.list], the elements of the initializer list are taken as initializers for the elements of the aggregate. 3当按[dcl.init.list]中指定的初始化器列表初始化聚合时,初始化器列表的元素将用作聚合元素的初始化器。 The explicitly initialized elements of the aggregate are determined as follows: 聚合的显式初始化的元素确定如下:

3.1 If the initializer list is a designated-initializer-list, the aggregate shall be of class type, the identifier in each designator shall name a direct non-static data member of the class, and the explicitly initialized elements of the aggregate are the elements that are, or contain, those members. 3.1如果初始化程序列表是指定的初始化程序列表,则聚合应为类类型,每个指示符中的标识符应命名该类的直接非静态数据成员,并且聚合中显式初始化的元素为元素是或包含这些成员。

3.2 If the initializer list is an initializer-list, the explicitly initialized elements of the aggregate are the first n elements of the aggregate, where n is the number of elements in the initializer list. 3.2如果初始化列表是初始化列表,则聚合中显式初始化的元素是聚合的前n个元素,其中n是初始化列表中的元素数。

3.3 Otherwise, the initializer list must be {} , and there are no explicitly initialized elements. 3.3 否则,初始化列表必须为{} ,并且没有显式初始化的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM