如何构造通过 std::allocator::allocate() 分配的对象?

问题描述

C++20 从 construct()删除destruct()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,allocated_size);
,

看起来 staticconstruct 形式仍然存在于 C++20 中。也许这是为了取代 construct 的原始形式?

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

我在自定义分配方面做得并不多,所以我没有使用这些函数的个人经验,但他们可能更喜欢静态函数以打破依赖关系似乎是合理的。

还有一个 construct_at 函数是在 C++20 中添加的。

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