考虑以下片段:
#include <iostream>
union U{
U(): i(1) {}
int i;
int j = 2; // this default member initializer is ignored by the compiler
};
U u;
int main(){
std::cout << u.i << '\n';
std::cout << u.j << '\n';
}
代码打印(参见 live example ):
1
1
标准中哪里说编译器忽略了成员 U::j
的默认成员初始值设定项?
请注意,下面的 union 不会编译,根据 [class.union.anon]/4 这是可以的.因此,我希望上面的代码片段也不会编译。
参见 live example :
union U{
int i = 1;
int j = 2;
};
最佳答案
Where in the Standard does it say that the default member initializer for the member U::j is ignored by the compiler?
请参阅 C++17 CD 中的 [class.base.init] 第 9 段项目符号 9.1。
注意你的演示有未定义的行为,因为联盟的活跃成员是 i
但你从 j
读取。这适用于某些编译器作为非标准扩展,但在 ISO C++ 中是不允许的。
关于c++ - 标准中哪里说 U::j 的默认成员初始值设定项应该被编译器忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633257/