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 =
TL;DR This is UB.
[basic.life]
Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor]. Otherwise, such a glvalue refers to allocated storage, and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if: [...]
- the glvalue is used to call a non-static member function of the object, or
By definition, an inactive member of an union isn't within its lifetime.
A possible workaround is to use C++20 [[no_unique_address]]
struct Point
{
int& get_x() { return xy[0]; }
int& get_y() { return xy[1]; }
[[no_unique_address]] property x;
[[no_unique_address]] property y;
std::array xy;
};
static_assert(offsetof(Point, x) == 0 && offsetof(Point, y) == 0);