如何构造通过std::allocator::allocate()分配的对象?
C ++ 20除去construct()和destruct()成员std::allocator。我应该如何构造通过 分配的对象std::allocator<T>::allocate()?我发现了std::uninitialized_fill()and std::uninitialized_copy(),但据我所知,它们不是分配器感知的,它们会进行复制,我认为这会对非 POD 类型的性能造成很大影响。
回答
您可以使用std::allocator_traits.
删除构造方法的重点是因为分配器特征已经具有该方法,并且std::allocator_traits::construct无论如何STL 容器都会使用。
cppreference 中的文档
这是一个小例子:(Alloc是任何分配器)
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);
THE END
二维码