Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I construct my objects allocated through std::allocator::allocate()?

C++20 removed the construct() and destruct() members from std::allocator. How am I supposed to construct my objects allocated through std::allocator<T>::allocate()? I found std::uninitialized_fill() and std::uninitialized_copy(), but as far as I understood they are not allocator-aware, and they do copies, which I think would hurt performance a lot for non-POD types.

like image 248
Guess Avatar asked Jul 26 '26 08:07

Guess


1 Answers

You can do it using std::allocator_traits.

The point of removing the construct method is because the allocator traits already has that method, and the STL containers use std::allocator_traits::construct anyway.

Documentation in cppreference

And here is a little example: (Alloc is any allocator)

Alloc a{};
std::allocator_traits<Alloc>::pointer i = std::allocator_traits<Alloc>::allocate(a, allocated_size);

// You use the construct and destroy methods from the allocator traits
std::allocator_traits<Alloc>::construct(a, i, value_to_construt);
std::allocator_traits<Alloc>::destroy(a, i);

std::allocator_traits<Alloc>::deallocate(a, i, allocated_size);
like image 154
Pablochaches Avatar answered Jul 28 '26 23:07

Pablochaches