c++ - 类 union 类中 `reinterpret_cast` 上的 `this` 是未定义的行为吗?

标签 c++ undefined-behavior unions

考虑以下代码:

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

  • 如果它是 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/

相关文章:

c++ - T 类型的左值必须标识 T 类型的对象吗?如果 `p` 的类型为 `T *` ,那么 `&*p` 是否需要 `p` 才能实际指向类型为 `T` 的对象?

c - 如何解释这个 C union 输出

c++ - 如何在关联指针时编写无错误代码?

c++ - 我不明白这个快速排序的实现

C++ 为什么它不是同一个地址(指针)

c - 加载未对齐的地址和 UBsan 发现

c - 为什么 C 数组的 5[a] 不会超出范围?

c - 对 union 中的字符进行 strcpy 时程序中止

c - 如果 union 的格式不同,C 如何解释来自 union 的数据?

c++ - 从输入文件中读取