Unions to extract data
Won't the union in this question cause UB when used as this:
union Data
{
uns开发者_运维知识库igned int intValue;
unsigned char argbBytes[4];
};
Data data;
data.intValue = 1235347;
unsigned char alpha = data.argbBytes[0]; //UB?
I'm thinking about 9.5/1 in the standard:
In a union, at most one of the data members can be active at any time, that is, the value of at most one of the data members can be stored in a union at any time.
in general you are right, writing a value of one type to a union then reading it out as a different type is undefined behaviour. on the other hand iirc the standard explicitly allows anything to castable as a char array. it's never been 100% clear to me which takes precedence, but all implementations I have ever used allow union casting to do what you want anyway.
I suppose that'd be undefined as what you've done is platform specific. alpha would end up as a different value depending on whether your platform is big-endian or little-endian.
But, the technique you show is pretty much equivalent to doing a reinterpret_cast.
I think the standard is pointing out that you can't store different values in both members (as they overlap in memory).
The real reason union's were invented were to allow people to fit more data in a smaller amount of memory. Traditionally, along with a union, you'd save some marker (perhaps a bit or two stored in a bitmask) outside of the union to remember which member of the union is active. Using this marker, you'd carefully code accesses to the union so you only read the active member.
It is not clear from the post as to what is the size of 'int' on the platform. Assuming 32-bit integer, and 8-bit character, i.e. sizeof(int) == 4.
It is also not clear what is the endian-ness of the machine. Let us assume small endian.
With that undertanding, 0x12D993 (decimal 1235347) would be stored as
0x93 0xd9 0x12 0x00 (increasing address)
When this memory is accessed through 'argbBytes', the value of argbBytes[0] really depends on the endian-ness of the machine. Therefore, it is not an Undefined Behavior but an Implementation Defined Behavior.
精彩评论