问题
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.
回答1:
Your code has undefined behavior. The initial common sequence rule wont help you here since you are not accessing a common member but instead you are accessing the entire object in order to call the member function1.
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};
The way to do this in C++ is to use a struct and operator overloading. Instead of having an array and trying to map it to individual members, you have individual members and then pretend that your class is an array. That looks like
struct vec
{
int x, y, z;
int& operator[](size_t index)
{
switch(index)
{
case 0: return x;
case 1: return y;
case 2: return z;
}
}
};
1: to call a member function is to pass that object to that function as if it was the first parameter of the function.
来源:https://stackoverflow.com/questions/62088651/call-member-function-of-non-active-union-member