简体   繁体   中英

Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well defined behavior?

If I have an union

union Bytes {
  std::uint16_t bytes;
  std::array<std::uint8_t, 2> split_bytes;
};

and I use it like this

int main(){
  auto bytes = Bytes{0xFF'EE};
  // do something with bytes.split_bytes[0] and bytes.split_bytes[1]
}

Assuming the target machine is little endian, is my usage well-defined behavior?

Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well defined behavior?

Reading an inactive union member is undefined behaviour. Assigning an inactive trivial union member activates it.

Since the target of your attempted type punning is std::uint8_t which is unsigned char , you can use reinterpret_cast to read a std::uint16_t . However, as you seem to be aware, the order of the bytes varies between systems, and making assumptions about the order will result in a poorly portable program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM