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/