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

标签 c++ std c++20 allocator

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/

相关文章:

c++ - 将 C++20 模板化 Lambda 传递给函数,然后调用它

c++ - C++是否支持抽象数组长度

c++ - 查找未排序的 vector<int>

c++ - wxWidgets:如何在不使用宏且不进入主应用程序循环的情况下初始化 wxApp?

c++ - 命名空间 'std' 中的“bad_cast”未命名类型错误

c++ - 通过 std::bind 传递右值

c++ - 如何在 C++ 中专门化可变参数模板函数?

c++ - 有没有一种干净的方法可以将模板参数转发给模板函数?

c++ - 将共享库与 GCC 链接时出现问题

c++ - 专门化命名空间中的模板——命名空间别名真的是别名吗?