I have a character array that contains “serialized” data that I need to interpret as ‘int’s. Previosuly I just cast a pointer to the location to an ‘int*’ and dereferenced that to get at the int data, but although it’s worked well for me it’s breaking the strict alias rules and therefore undefined behavour.
So now I use memcpy to copy the bytes into an int, which I believe is not undefined behavour. However can I use “std::copy”?
For example
char data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int i;
std::copy(data, data+sizeof(int), reinterpret_cast<char*>(&i));
This in itsself doesn’t break the strict alias rules but any likely implementation will do so… However memcpy has the same issue and that’s “allowed”.
Is this standard compilant code or do I need to stick to using memcpy?
EDIT: I should add that I appeciate the answers on how best to do this, they are interesting, but my question was more about is this legal than how can I do this.
This is equivalent to
std::memcpy(&i, data, sizeof(int))and suffers the same problems of relying on endianness and the assumption thatsizeof(int) <= sizeof(data), which are platform-dependent.char *is exempt from the strict aliasing rule.