C++ Logo

std-discussion

Advanced search

Re: UB in P2641 'Checking if a union alternative is active'

From: language.lawyer_at <language.lawyer_at_[hidden]>
Date: Tue, 20 Jun 2023 00:48:02 +0500
>>> Given:
>>>
>>> int main() {
>>> union U { int i; char c; };
>>> U u{.i=1};
>>>
>>> char c1 = (char&)u;
>>> char c2 = (char&)u.i;
>>> char c3 = u.c;
>>> return c1 + c2 + c3;
>>> }
>>>
>>> c1, c2, and c3 are obviously equivalent here. If there's wording to suggest otherwise, that's a wording defect.
>>
>> c1 and c2 are equivalent to c3 (and each other), which means UB due to dead object access for all 3 cases.
>
> How so? c1 is a punned reference to u, and c2 is a punned reference to u.i

No idea what «punned reference» is. Which cast (char&) is equivalent to? (https://timsong-cpp.github.io/cppwp/n4868/expr.cast#4.sentence-1)

Received on 2023-06-19 19:48:09