c++ - 您是否可以使用 std::aligned_union 违反严格的别名规则

标签 c++ c++11 undefined-behavior unions strict-aliasing

执行 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 也同样安全与安置newreinterpret_cast构建并获得正确的值?

(假设 AB 为标准布局)

最佳答案

当核心语言说“union”时,它的意思是“union”,即“用class-keyunion定义的类”。不是称为 aligned_union_t 的可悲的库模仿。

关于c++ - 您是否可以使用 std::aligned_union 违反严格的别名规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48158866/

相关文章:

c++ - 不同风格的 shared_ptr 之间的差异

c++ - 指向释放变量的指针更改地址

c - 使用移位/屏蔽遇到奇怪的行为

c++ - 是否可以从基类调用派生类的方法?例如;避免 'slicing'

c++ - 无法在 BackgroundSubtractorMOG2 中设置用户参数

c++ - 在用C++初始化对象时遇到问题-Linux

c++ - 如何解决这个歧义?

c++ - 静态链接 C++ OpenCV

c - 获取未初始化指针的地址是未定义的行为吗?

c++ - 无限循环的形式不好吗?