8

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.

Community
  • 1
  • 1
Dan
  • 12,409
  • 3
  • 50
  • 87

2 Answers2

13

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

Try std::aligned_storage instead.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • Alignment! Of course it's something that didn't even occur to me. Thanks for that link, that's exactly what I needed. – Dan Nov 08 '12 at 00:53
0

It doesn't matter what the array is contained in.

The standard does not even consider what surrounds something (it's that basic), but does support conversion to/from char sequences.

To do this directly via reinterpret_cast and assignment, you need to have the buffer correctly aligned.

An alternative is to use memcpy, which doesn't care about alignment.

On a related issue, it's generally not a good idea to go down to the binary level. For example, a simple version change of the compiler might make a file of binary-serialized data inaccessible. A main driver for doing this anyway is raw performance considerations.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Does it support converting an arbitrary `char*` to `double*`? I think the pointer conversion may be lossy. Consider an ABI with different sized pointers. – Potatoswatter Nov 08 '12 at 00:55
  • What kind of compiler change could cause that to happen? – Dan Nov 08 '12 at 00:56
  • A `char` pointer has as fine-grained addressing resolution as any pointer, same as with `void`. The pointer conversion can conceivably be lossy if the buffer isn't correctly aligned. Anyway the data copying can then be *inefficient*. – Cheers and hth. - Alf Nov 08 '12 at 00:59