I want to build an object of arbitrary type inside with place-new std::aligned_union_t
. After a successful build, I want to be able to return a pointer to the constructed object without saving it separately. Is it legal to do this just reinterpret_cast
'in std::aligned_union_t
if I guarantee that I applied it to the original type that was created?
Is the following code illustrating the above legal? Are there any type requirements that MyStruct
must be met for this to be the case? For example, should it 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;
}
source
share