C++ Logo


Advanced search

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

From: M.P. <dbc_at_[hidden]>
Date: Sun, 18 Jun 2023 21:49:46 -0000
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;

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?

Received on 2023-06-18 21:50:08