Accessing inactive union members through char
7 days ago
- #Undefined Behavior
- #Aliasing Rules
- #C++
- The article discusses a C++26 standard library facility, std::is_within_lifetime, and addresses concerns about undefined behavior (UB) in an example from its proposal.
- A specific example involves accessing an inactive union member through a char, which initially seems like UB but is actually valid due to C++ aliasing rules.
- C++ allows accessing any object's representation through char, unsigned char, or std::byte types, making the example valid.
- The article explains that character types can alias any object in memory, a rule rooted in C++'s C heritage.
- This exception in the aliasing rules ensures that inspecting raw representation via character types is not UB.
- The conclusion emphasizes understanding such fine print in the C++ standard to write truly correct code.