Does calling foo in the following code leads to UB?
using vec = std::array<int, 1>;
struct field0 {
vec data;
operator int() {
return data[0];
}
};
union a {
struct {
vec data;
} data;
field0 x;
};
void foo() {
a bar;
std::cin >> bar.data.data[0];
std::cout << bar.x;
}
According to standard, x and data have the same address, so it should be safe to cast this to vec*. Also, field0 and vec are layout-compatible, so it should be safe to inspect data via x.data or vice-versa.
However, we not just inspect x.data, we call non-static member function of x outside of it's lifetime (or do we? I can't find a reason why x lifetime should have started), so formally it's UB. Is it correct?
What I am trying to achieve is well-defined version of common approach to name array field like union a { int data[3]; int x, y, z};
UPD:
Sorry, during removing unnecessary details, layout compatibility between array field and "getter" was lost. Restored now.
I will need to use
avalues to function that takesint*, so going in other direction - declaring fields and overloadingoperator[]- is not an option.