Call member function of non-active union member

送分小仙女□ 提交于 2021-02-16 20:18:37

问题


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:

  1. Sorry, during removing unnecessary details, layout compatibility between array field and "getter" was lost. Restored now.

  2. I will need to use a values to function that takes int*, so going in other direction - declaring fields and overloading operator[] - 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!