I have (re?)invented this approach to zero-cost properties with data member syntax. By this I mean that the user can write:
some_struct.some_member = var;
var =
Here is what the common-initial-sequence rule says about unions:
In a standard-layout union with an active member of struct type
T1
, it is permitted to read a non-static data memberm
of another union member of struct typeT2
provided m is part of the common initial sequence of T1 and T2; the behavior is as if the corresponding member of T1 were nominated.
Your code does not qualify. Why? Because you are not reading from "another union member". You are doing m.x = 42;
. That isn't reading; that's calling a member function of another union member.
So it doesn't qualify for the common initial sequence rule. And without the common-initial-sequence rule to protect you, accessing non-active members of the union is UB.