gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:15:04 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com