struct header
{
int a1;
int a2;
// ...;
std::byte * get_data_bytes()
{
return align_up<data>( // make sure alignment requirements are met
reinterpret_cast<std::byte *>(this) + sizeof(*this));
// maybe std::launder around the reinterpret_cast (only) is needed?
}
data & get_data()
{
return *std::launder(reinterpret_cast<data *>(get_data_bytes()));
}
void use_data()
{
get_data().use();
}
};
void example()
{
alignas(header) std::byte storage[/* plenty of space*/];
auto h = new (storage) header;
new (h->get_data_bytes()) data;
h->use_data(); // Does this eventually cause a UB?
}
Is this possible without UB? If not, is there an alternative? The requirement is that data is not a subobject of the header and there is no pointer/reference to the data from the header to avoid additional indirection. This could maybe be possible with flexible empty array but I don't think these are in the standard.