c++ - 标准中哪里说 U::j 的默认成员初始值设定项应该被编译器忽略?

标签 c++ language-lawyer unions c++17

考虑以下片段:

#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/

相关文章:

c++ - 使用 boost::multi_index reverse_iterators

c - 从文件读取时 union 导致段错误

c - Union 比 C 中的 Structure 更好的选择的场景

hive 查询特定联合类型的记录

c++ - POD的零初始化

c++ - 将文件内容作为参数传递给 C++ 程序

C++ 无法将成对的指针初始化为 NULL

c++ - 使用可变函数模板的奇怪重载决议

c++ - 为什么 std::ssize 被强制为其带符号大小类型的最小大小?

c++ - int a[] = {1,2,};为什么允许在初始化列表中使用尾随逗号?