c++ - 为什么 MSVC 和 GCC 不能使用具有默认值的字段初始化结构

标签 c++ gcc visual-c++ clang language-lawyer

int main() {
  struct WorkItem {
    int node;
    unsigned predecessorIndex = 0;
  };  

  auto x = WorkItem { 0 };

  return 0;
}

这段代码可以用 Clang 编译,但不能用 GCC:

source_file.cpp: In function ‘int main()’:

source_file.cpp:9:25: error: no matching function for call to ‘main()::WorkItem::WorkItem()’ auto x = WorkItem { 0 }; ^

source_file.cpp:9:25: note: candidates are:

source_file.cpp:4:10: note: main()::WorkItem::WorkItem() struct WorkItem { ^

source_file.cpp:4:10: note: candidate expects 0 arguments, 1 provided

source_file.cpp:4:10: note: constexpr main()::WorkItem::WorkItem(const main()::WorkItem&)

source_file.cpp:4:10: note: no known conversion for argument 1 from ‘int’ to ‘const main()::WorkItem&’

source_file.cpp:4:10: note: constexpr main()::WorkItem::WorkItem(main()::WorkItem&&)

source_file.cpp:4:10: note: no known conversion for argument 1 from ‘int’ to ‘main()::WorkItem&&’

或 MSVC:

source_file.cpp(9): error C2440: 'initializing': cannot convert from 'initializer list' to 'main::WorkItem'

source_file.cpp(9): note: No constructor could take the source type, or constructor overload resolution was ambiguous

从标准的角度来看,Clang 是否错误地编译了这段代码,或者 MSVC 和 GCC 是错误的? 另外,为什么删除 = 0 允许 GCC 和 MSVC 编译?例如

int main() {
  struct WorkItem {
    int node;
    unsigned predecessorIndex = 0;
  };  

  auto x = WorkItem { 0 };

  return 0;
}

海湾合作委员会版本:4.9.3 铿锵版本:3.7.0 MSVC版本:19.00.24215.1

最佳答案

GCC version: 4.9.3

使用默认成员初始化器进行聚合初始化是 GCC does not support until GCC 5.x 的一项 C++14 功能.

MSVC version: 19.00.23506

我相信这是 VC 2015 的更新 1。使用默认成员初始化程序进行聚合初始化是 VC doesn't support until 2017 的一项 C++14 功能。 .

关于c++ - 为什么 MSVC 和 GCC 不能使用具有默认值的字段初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41348082/

相关文章:

c++ - 用宏确定GCC编译器

linux - 在 fedora 上运行 gcc 获取 AVR

c++ - 如何使用 flashlite 作为前端创建桌面应用程序?

c++ - 有条件地替换字符串中的正则表达式匹配

c++ - 替换 findfirst() 和 findnext()

c++ - `class<T>` 到 `class<const T>` 转换运算符的惯用方式

c++ - 如何根据参数的调用运算符参数或存在来重载模板函数?

c++ - 指向结构体的双指针

c++ - 使用 SSE 内在函数将 boolean 数组(8 字节 boolean )转换为 int 或 char

c++ - 以字符数组为参数的模板元编程