Is the static memory section alignas(alignof(T)) char bytes[sizeof(T)]
suitable to hold an instance of T
during its lifetime by calling std::construct_at(bytes, ...)
/ std::destroy_at(bytes)
? My instincts say, yeah, the alignment and size requirements are guaranteed, so after construction (since there are also trivially constructible types, I prefer to call it initialization) reinterpret_cast<T*>(bytes)
is a valid pointer to a completely valid instance of type T
.
Am I missing something?
PS: I could also write std::aligned_storage_t<sizeof(T), alignof(T)> bytes
- in that case its memory would be referenced as &bytes
or std::addressof(bytes)
.
Is the static memory section
alignas(alignof(T)) char bytes[sizeof(T)]
suitable to hold an instance of T during its lifetime by callingstd::construct_at(bytes, ...)
/std::destroy_at(bytes)
?
Yes.
reinterpret_cast<T*>(bytes)
is a valid pointer to a completely valid instance of type T.Am I missing something?
You would still need to launder a pointer to reused memory:
T* ptr1 = std::construct_at(reinterpret_cast<T*>(bytes), ...); // valid
T* ptr2 = std::launder(reinterpret_cast<T*>(bytes)); // valid
std::destroy_at(ptr2); // valid, just like std::destroy_at(ptr1)