I want to construct using placement-new an object of arbitrary type inside a std::aligned_union_t
. Once constructed successfully, I want to be able to get back the pointer to the constructed object without storing it separately. Is it legal to do so by simply reinterpret_cast
'ing the std::aligned_union_t
, as long as I ensure that I cast it to the original type that was constructed?
Is the following code that exemplifies the above, legal? Are there any type trait requirements that MyStruct
should satisfy for it to be so? For instance, does it have to be a POD?
#include <type_traits>
#include <memory>
#include <cstddef>
#include <exception>
struct MyStruct
{
int value = 0;
};
constexpr size_t c_alignedUnionSize = 10;
std::aligned_union_t<c_alignedUnionSize, std::max_align_t> g_storage;
MyStruct* GetPtr()
{
return reinterpret_cast<MyStruct*>(std::addressof(g_storage));
}
void Construct()
{
if (sizeof(MyStruct) > sizeof(g_storage))
{
std::terminate();
}
auto ptr = new (std::addressof(g_storage)) MyStruct{};
if (!ptr)
{
std::terminate();
}
GetPtr()->value = 123;
}
void Destroy()
{
GetPtr()->~MyStruct();
}
int GetValue()
{
return GetPtr()->value;
}
int main()
{
Construct();
auto value = GetValue();
Destroy();
return value;
}