union for uint32_t and uint8_t[4] undefined behavior? [duplicate]

I don’t know what means What’s UB in C++ is to access inactive union members.

Basically what it means is that the only member you can read from a union without invoking undefined behavior is the last written one. In other words, if you write to addr32, you can only read from addr32, not addr8 and vice versa.

An example is also available here.

Edit: Since there has been much discussion if this is UB or not, consider the following (fully valid) C++11 example;

union olle {
    std::string str;
    std::wstring wstr;
};

Here you can definitely see that activating str and reading wstr may be a problem. You could see this as an extreme example since you even have to activate the member by doing a placement new, but the spec actually covers this case with no mention that it’s to be considered a special case in other ways regarding active members.

Leave a Comment