In a variant class I'm working on the raw storage is a char array:
alignas(/* the strictest alignment of all types of the variant */)
char storage[/* ... */];
The 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 for getting the stored object is:
template<class X>
const X &get()
{
// ...
return *reinterpret_cast<X *>(storage);
// ...
}
It seems to work but is it always well defined? I'm worried about safely dereferencing the pointer (is it allowed by the type aliasing rules?).
Are there any differences between the current implementation and
return *static_cast<const X *>(static_cast<const void *>(storage));
Related question/answer:
https://mcmap.net/q/16600/-do-i-understand-c-c-strict-aliasing-correctly (see James Kanze's comments).
EDIT
Second question already has an answer here: C++ When should we prefer to use a two chained static_cast over reinterpret_cast
new(storage) X(x);
is a memory leak – Fishtail