在类似工会的类中,“reinterpret_cast”上的“这个”是一种未定义的行为吗?



请考虑以下代码:

#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_tB

  • 如果它是B那么演员表是非法的(因为它不是uint32_t你不能投到它(。
  • 如果是uint32_t那么打电话给.c()成员是非法的,因为您无法访问b1成员(不是活跃的工会成员(。

在这种情况下(感谢@StoryTeller的评论(,活动工会成员a(uint32_t(,因为它是唯一具有默认初始化的成员,因此调用a.b1.c()是UB。

相关内容

最新更新