std::copy_n and reinterpret_cast
-
14-07-2021 - |
Question
uint data1;
ushort data2;
ushort data3;
uchar data4[8];
std::uint8_t buff[16];
std::uint8_t* out = buff;
out = std::copy_n(reinterpret_cast<std::uint8_t*>(&quid.data1), 4, out);
out = std::copy_n(reinterpret_cast<std::uint8_t*>(&quid.data2), 2, out);
out = std::copy_n(reinterpret_cast<std::uint8_t*>(&quid.data3), 2, out);
std::copy_n(quid.data4, 8, out);
Why will the result in out
will be different if I don't use reinterpret_cast
?
Solution
The result will be different because &x
has type T *
, where T
is the type of x
, and pointer arithmetic treats + 1
as "advancing the pointer by sizeof(T)
", so that in effect you treat a pointer as a pointer into an array of elements of that type.
If you change the type of the pointer, you're going to treat the memory it's pointing to as an array of elements of a different type -- for example, treating an int
as an array of char
s.
OTHER TIPS
std::copy_n(&quid.data1, 4, out);
works as if quid.data1
were declared as uint data1[4]
. The result is that quid.data1
is copied to out[0]
and the 3 other elements of out
get a garbage.
std::copy_n(reinterpret_cast<std::uint8_t*>(&quid.data1), 4, out);
treats the contents of data1
as an array of 4 chars, that would work if sizeof(uint)==4
.