考虑以下代码:
#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 都是一个类似 union 的结构。我的问题是,假设 A 满足 StandardLayoutType概念,是否将 this
转换为 B::c
以获取指向 A::a
未定义行为的指针?
最佳答案
这是未定义的行为。总的来说, union 包含 uint32_t
或 B
。
- 如果它是
B
,则强制转换是非法的(因为它不是uint32_t
,您不能向它强制转换)。 - 如果它是一个
uint32_t
那么调用.c()
成员是非法的,因为您不能访问b1
成员(isn '活跃的 union 成员)。
在这种情况下(感谢 @StoryTeller's 评论)活跃的 union 成员是 a
(uint32_t
),因为它是唯一具有默认初始化的成员,因此调用 a.b1.c()
是 UB。
关于c++ - 类 union 类中 `reinterpret_cast` 上的 `this` 是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48277466/