【发布时间】:2018-06-24 22:31:24
【问题描述】:
考虑以下代码:
#include <cstdint>
struct B {
uint32_t c() {
uint32_t * value = reinterpret_cast<uint32_t *>(this);
return * value;
}
};
struct A {
union {
B b1;
B b2;
uint32_t a { 10 };
};
};
int test() {
A a;
return a.b1.c();
}
这里test() 返回 10,因为所有 A 都是类似联合的结构。我的问题是,假设 A 满足 StandardLayoutType 概念,是否在 B::c 内转换 this 以获取指向 A::a 未定义行为的指针?
【问题讨论】:
-
这个
return * value;是未定义的行为。 -
在 C++ 中访问联合的非活动成员始终是 UB
-
你为什么不用
std::variant? -
@Boiethios 我没有实现变体容器——我正在尝试定义明确的位域访问
-
@JohnDoe 我只是想说,当
variant存在时,没有理由在现代C++ 中使用union。
标签: c++ undefined-behavior unions