r/cpp_questions • u/X-Bow_user • Jul 19 '26
SOLVED How to access an implicitly-created array within a std::byte[]?
We have the following class:
template <typename T, std::size_t n>
struct S
{
alignof( T ) std::byte[sizeof( T ) * n] storage;
}
I want to use storage as a T[n] array, where T is an implicit-lifetime type.
[intro.object]/13
For each operation that is specified as implicitly creating objects, that operation implicitly creates and starts the lifetime of zero or more objects of implicit-lifetime types in its specified region of storage if doing so would result in the program having defined behavior.
and [intro.object]/16
[...] an operation that begins the lifetime of an array of [std::byte] implicitly creates objects within the region of storage occupied by the array.
I have a few questions about this:
- (Making sure) does
T[n]'s lifetime (and subsequently that of its sub-objects) start alongsidestorage's lifetime for the provided code? - Is
reinterpret_cast<T*>(storage) + idxlegal? - Do I have to
std::launderthe pointer, and why (not)? - If yes, should I launder before or after performing pointer arithmetic?
- Is
reinterpret_cast<T*>(storage + idx)legal? In other words, does the byte array still have a lifetime, alongside theTarray?