C++11 POD结构初始化错误

C++11 POD structure initializing error

我对简单代码感到困惑:

struct Item {
    size_t span{};
};

int main() {
    Item item{1}; // error is here
    return 0;
}

编译时出现以下错误:

test.cpp: In function ‘int main()’:
test.cpp:8:13: error: no matching function for call to ‘Item::Item(<brace-enclosed initializer list>)’
     Item i{1};
             ^
test.cpp:8:13: note: candidates are:
test.cpp:3:8: note: constexpr Item::Item()
 struct Item {
        ^
test.cpp:3:8: note:   candidate expects 0 arguments, 1 provided
test.cpp:3:8: note: constexpr Item::Item(const Item&)
test.cpp:3:8: note:   no known conversion for argument 1 from ‘int’ to ‘const Item&’
test.cpp:3:8: note: constexpr Item::Item(Item&&)
test.cpp:3:8: note:   no known conversion for argument 1 from ‘int’ to ‘Item&&’

在这种情况下,为什么 g++ 尝试为 initializer list 寻找 ctor 而不是创建简单的 C 风格结构对象?

如果我从 size_t span{} 中删除 {},它会成功编译。

如果我将行更改为 size_t span = 0 也会发生这种情况,所以它似乎是自 c++11 以来就存在的一些声明初始化问​​题。

Usign Item item{1}; 表示您正在进行 列表初始化item)。列表初始化定义如下:

  • 如果类型是聚合,聚合初始化(你所说的"C-style struct object creating")发生
  • ...
  • 如果类型是 class,则考虑构造函数

您的 class 没有构造函数。它也不是 (C++11) 聚合,因为它包含非静态数据成员的初始化程序。

请注意,此限制(成员初始化器)已在 C++14 中取消,因此 Item C++14 聚合和您的代码,而不是有效的 C++11,是有效的 C++14。