执行 union 规则,例如 [class.mem]
p20 还允许 std::aligned_union_t
?例如,如果我将两对( pair<const A, B>
和 pair<A, B>
)存储在 std::aligned_union_t
中非常量对始终处于事件状态。正在访问pair<const A>
键入违反严格别名规则?
该标准似乎暗示[class.mem]
p20 即使非 const 对处于事件状态,访问该对的 const 成员也是安全的
union U {
std::pair<A, B> pair;
std::pair<const A, const B> const_pair;
};
U u = {A{}, B{}};
cout << u.const_pair.first << endl;
cout << u.const_pair.second << endl;
但是 std::aligned_union
也同样安全与安置new
和reinterpret_cast
构建并获得正确的值?
(假设 A
和 B
为标准布局)
最佳答案
当核心语言说“union”时,它的意思是“union”,即“用class-keyunion
定义的类”。不是称为 aligned_union_t
的可悲的库模仿。
关于c++ - 您是否可以使用 std::aligned_union 违反严格的别名规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48158866/