Reinterpret_cast / static_cast and undefined

In the options class, I'm working on raw storage - a char array:

alignas(/* the strictest alignment of all types of the variant */) char storage[/* ... */]; 

An assignment operator is something like:

 template<class X> void operator=(const X &x) { // ...code for clearing the storage and setting the tag for type X... new(storage) X(x); } 

while the code to get the stored object:

 template<class X> const X &get() { // ... return *reinterpret_cast<X *>(storage); // ... } 

It seems to work, but is it always clearly defined? I worry about safely dereferencing a pointer (is this permissible by rules such as anti-aliasing?).

Are there any differences between the current implementation and

  return *static_cast<const X *>(static_cast<const void *>(storage)); 

Related Question / Answer:

https://stackoverflow.com/questions/8468/ ... (see James Kanze's comments ).


EDIT

The second question already has an answer here: C ++. When do we prefer to use the dug-up static_cast by reinterpret_cast

+7
c ++ c ++ 11 static-cast reinterpret-cast variant
source share
1 answer

As storage correctly aligned, I cannot imagine where the problem might arise. Paragraph (*) 4.10 on pointer conversions says: โ€œA value of typeโ€œ pointer to cv T โ€, where T is an object type, can be converted to prvalue of typeโ€œ pointer to cv void. โ€The result of converting the value of a non-zero pointer to an object type to "cv void pointer" represents the address of the same byte in memory as the original pointer value.

Regarding your second question, paragraph 5.2.10 on reinterpres_cast : an object pointer can be explicitly converted to an object pointer of another type. When the prvalue v of the object pointer type is converted to the cv T pointer object pointer type, the result is static_cast<cv T*>(static_cast<cv void*>(v)) , where cv stands for optional const or volatile .

Thus, this part is guaranteed to specifications. Moreover, as we saw that the cast to void * should point to the first byte of memory, for my understanding of the standard there is no UB if the compilers have the same understanding; -)

(*) Rรฉfรฉrence: Draft for current C ++ specification

+4
source share

All Articles