请考虑以下代码:
#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
未定义行为的指针?
这是未定义的行为。作为概述,联合包含uint32_t
或B
。
- 如果它是
B
那么演员表是非法的(因为它不是uint32_t
你不能投到它(。 - 如果是
uint32_t
那么打电话给.c()
成员是非法的,因为您无法访问b1
成员(不是活跃的工会成员(。
在这种情况下(感谢@StoryTeller的评论(,活动工会成员a
(uint32_t
(,因为它是唯一具有默认初始化的成员,因此调用a.b1.c()
是UB。