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

Vic*_*voy 2 c++ initialization initializer-list c++11

我有简单的代码令人困惑的情况:

struct Item {
    size_t span{};
};

int main() {
    Item item{1}; // error is here
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在编译时我有以下错误:

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&&’
Run Code Online (Sandbox Code Playgroud)

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

如果我{}从中删除size_t span{}编译成功.

如果我将行更改为,size_t span = 0那么它也会发生,因此它似乎是自c ++ 11以来存在的声明问题中的一些初始化.

Rei*_*ica 5

Usign Item item{1};意味着你正在进行列表初始化(of item).列表初始化定义如下:

  • 如果类型是聚合,则会发生聚合初始化(您称之为"C风格的结构对象创建")
  • ...
  • 如果类型是类,则考虑构造函数

你的班级没有构造函数.它也不是(C++ 11)聚合,因为它包含非静态数据成员的初始化.

请注意,此限制(成员初始化程序)在C++ 14中被取消,因此Item 是 C++ 14聚合,而您的代码虽然不是有效的C++ 11,但却是有效的C++ 14.