Markus said:
Jakob Bieling wrote:
I cannot see from 9.5 that my example leads to undefined behaviour. Why
do you think so?
I think it is more implementation defined, no?
9.5 however does clarify that unions guarantee correctly aligned memory
layout: "Each data member is allocated as if it were the sole member of
a struct."
3.10 (15) Furthermore resolves aliasing issues for unions (it also
mentions that they are not an issue with char anyway).
Everything in a union /starts/ at the same place and is no different
in/out of the union, but that doesn't fix the other problems...such as
padding in the struct. However, if the data on both sides looks
exactly the same then we can expect the correct result on the other
side. But there is no guarantee that they are...packet_t could be
different on one side vs. the other...especially if being sent from a
machine with a different way of byte allignment in ints.
I don't know what aliasing issues you are refering to. I think both
methods work under different situations and neither is perfect as there
are undefined or implementation defined issues in both answers. Using
a union can be quite clean if you know certain things ahead of time and
can be pretty sure none of the variants can occur...copying the values
individually using reinterpret_cast on both sides can have less padding
issues...really, the correct answer is going to be more complex than
either and requires explicit alignment of the data packet in a
guaranteed fassion. The union method does what the OP was doing in the
first place in a cleaner way...