C++ Logo

std-discussion

Advanced search

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

From: Matthew House <mattlloydhouse_at_[hidden]>
Date: Mon, 19 Jun 2023 15:42:13 -0400
On Mon, Jun 19, 2023 at 3:37 PM language.lawyer--- via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
> > 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.
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion

How so? c1 is a punned reference to u, and c2 is a punned reference to
u.i, so [basic.lval]/11 applies, does it not? Meanwhile, reading u.c
for c3 would access an inactive variant.

Received on 2023-06-19 19:42:26