Следующий код демонстрирует типичное использование std::launder:
Код: Выделить всё
template
struct MyAllocator
{
MyAllocator()
{
for (std::byte& b : data)
b = std::byte{0};
}
std::byte data[N];
std::size_t sz{N};
void* p{data};
// Note: only well-defined for implicit-lifetime types
template
T* implicit_aligned_alloc(std::size_t a = alignof(T))
{
if (std::align(a, sizeof(T), p, sz))
{
T* result1 = reinterpret_cast(p);
T* result2 = std::launder(result1);
p = static_cast(p) + sizeof(T);
sz -= sizeof(T);
return result2;
}
return nullptr;
}
};
struct A { int x; };
int main()
{
MyAllocator a;
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79827424/using-stdlaunder-with-reinterpret-cast[/url]
Мобильная версия