Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this use of std::array undefined behavior? [duplicate]

Possible Duplicate:
Aliasing `T*` with `char*` is allowed. Is it also allowed the other way around?

I'm using a std::array of chars 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 chars 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.

like image 569
Dan Avatar asked Nov 08 '12 00:11

Dan


1 Answers

Yes, std::array< char, 10 > does not satisfy the alignment requirements of double so that reinterpret_cast provokes UB.

Try std::aligned_storage instead.

like image 177
Potatoswatter Avatar answered Oct 29 '22 17:10

Potatoswatter