问题
At work we have the following construct to enable interpreting an IP address as either an array of 4 bytes, or as a 32-bit integer:
union IPv4
{
std::uint32_t ip;
std::uint8_t data[4];
};
This works fine, but I'm a little worried after reading chapter 97 "Don't use unions to reinterpret representation" of the book C++ coding standards. The example in the book is more insidious though and I'm not sure if it applies to my code.
Are there any potential issues with my code?
回答1:
According to the standard, reading a member of a union other than the last one written is undefined behavior. Unions were designed to save space, no for data type conversion. That said, what you are doing will probably work on all mainstream platforms and compilers.
回答2:
No problem, as the represantation is the same you just access ist differently.
来源:https://stackoverflow.com/questions/3263239/using-a-union-for-multiple-interpretations-of-ip-address