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

Viewed 886

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.

2 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);

It looks like a static form of construct still exists in C++20. Maybe that is intended to replace the original form of construct?

https://en.cppreference.com/w/cpp/memory/allocator_traits/construct

I have not really done much with custom allocation so I don't have personal experience using these functions, but it seems reasonable that they might prefer a static function in an effort to break dependencies.

There is also a construct_at function that is added with C++20.

https://en.cppreference.com/w/cpp/memory/construct_at

Related