给定以下代码:
struct A { int i; };
struct B { std::string s; };
struct C
{
union
{
A a{};
B b;
};
};
以下访问是否定义良好:
void foo()
{
C c; // c.a is active
c.b = {}; // now c.b is active
auto& b = reinterpret_cast<B&>(c.a); // read c.b via access to c.a
// use b somehow
}
reinterpret_cast<B&>(c.myUnion)
是可以的,而reinterpret_cast<B&>(c.myUnion.a)
不行。我通常使用constexpr
函数来检查 UB,但不幸的是,reinterpret_cast
不是constexpr
。 :/ - Jarod42