[英]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?
是否正在访问 std::array<std::uint8_t, 2> 而 std::uint16_t 在联合明确定义的行为中处于活动状态?
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
.由于您尝试的类型双关语的目标是
std::uint8_t
,它是unsigned char
,您可以使用reinterpret_cast
来读取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.但是,您似乎知道,字节的顺序因系统而异,并且对顺序进行假设将导致程序移植性差。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.