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: Mon, 19 Jun 2023 04:07:33 +0500
> I'm a bit confused by the OptBool examples from P2641
> (https://wg21.link/p2641#introduction). The paper claims that both are
> free from undefined behavior.
>
> Reduced case #1:
>
> union {
> bool b = true;
> char c;
> } u;
> +u.c;
>
> This reads from an inactive union member of type 'char'. The paper says
> that this is OK because of [basic.lval]/11.3, but I don't see how it
> applies here: we're not accessing a 'bool' through a glvalue of type
> 'char', we're accessing a distinct 'char' object outside its lifetime,
> which is undefined per [basic.life]/7.1.
>
> Reduced case #2:
>
> char c;
> new(&c) bool(true);
> +c; // #1
> +(bool&)c; // #2
>
> Creating a 'bool' in the storage associated with a 'char' ends the
> lifetime of the latter ([basic.life]/1.5), meaning #1 once again tries
> to access an object outside its lifetime. #2 does the same except
> through a 'bool' glvalue, additionally running afoul of [basic.lval]/11.
>
> Is there a mistake in the paper, or am I misunderstanding something?

Your analysis is correct, I've pointed at the same things in Core reflector half a year ago, and got no reaction from the authors. Not sure what does it mean. 🌚

Received on 2023-06-18 23:07:40