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

Empty nested initializer list in C++

考虑这段代码:

struct S {
    float b;
    int a;    
};

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

Godbolt

Clang 6.0.0 编译此代码,但显示警告:

<source> warning: too many braces around scalar initializer [-Wmany-braces-around-scalar-init]

GCC 8.2不编译这段代码并报错:

<source>: In function 'int main()': <source>:9:10: error: braces around scalar initializer for type 'float'

哪个是正确的?规范对此有何规定?

两个编译器都是正确的。除非您违反了 不需要诊断 的规则,否则编译器应该向您发出一条消息。该消息是警告还是错误取决于实现。通常情况下,如果编译器仍然可以继续处理,您会收到警告;如果编译器无法继续处理,则会收到错误。

What does the specification say about this?

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. 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.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.3 Otherwise, the initializer list must be {}, and there are no explicitly initialized elements.