C++20 删除了 construct()
和 destruct()
成员(member)来自 std::allocator
.我应该如何构造通过 std::allocator<T>::allocate()
分配的对象?我找到了 std::uninitialized_fill()
和 std::uninitialized_copy()
,但据我所知,它们不是分配器感知的,它们会进行复制,我认为这会对非 POD 类型的性能造成很大影响。
最佳答案
你可以使用 std::allocator_traits
.
删除构造方法的重点是因为分配器特征已经具有该方法,并且 STL 容器使用 std::allocator_traits::construct
反正。
Documentation in 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);
关于c++ - 如何构造通过 std::allocator::allocate() 分配的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65526419/