Using a union for multiple interpretations of IP address?

て烟熏妆下的殇ゞ 提交于 2019-12-07 18:06:59

问题


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

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