Possible Duplicate:
Aliasing `T*` with `char*` is allowed. Is it also allowed the other way around?
I'm using a std::array
of char
s to hold a value of unknown primitive type, which is no more than 10 bytes long, like so:
std::array<char, 10> val;
*reinterpret_cast<double*>(val.data()) = 6.3;
//blah blah blah...
double stuff = *reinterpret_cast<double*>(val.data());
I have read that casting back and forth through char *
is not undefined, because the compiler assumes a char *
may alias a value of any type. Does this still work when the value is placed in (what I assume is) an array of char
s inside the object?
Note: I am aware that I could be using a union here, but that would result in a large amount of boilerplate code for what I am doing, and I would like to avoid it if necessary, hence the question.
Yes, std::array< char, 10 >
does not satisfy the alignment requirements of double
so that reinterpret_cast
provokes UB.
Try std::aligned_storage
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With