如何构建通过 std::allocator::allocate() 分配的对象?
How can I construct my objects allocated through std::allocator::allocate()?
C++20 从 std::allocator
中删除了 construct()
和 destruct()
成员。我应该如何构建通过 std::allocator<T>::allocate()
分配的对象?我找到了 std::uninitialized_fill()
和 std::uninitialized_copy()
,但据我所知,它们不是分配器感知的,并且它们会进行复制,我认为这会对非 POD 类型的性能造成很大影响。
看起来 construct
的 static
形式仍然存在于 C++20 中。也许那是为了取代 construct
?
的原始形式
https://en.cppreference.com/w/cpp/memory/allocator_traits/construct
我在自定义分配方面做得并不多,所以我没有使用这些函数的个人经验,但他们可能更喜欢静态函数以打破依赖关系似乎是合理的。
还有一个construct_at
函数是C++20新增的
您可以使用 std::allocator_traits
。
删除 construct 方法的关键是因为分配器特征已经有了该方法,而 STL 容器仍然使用 std::allocator_traits::construct
。
这是一个小例子:(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++20 从 std::allocator
中删除了 construct()
和 destruct()
成员。我应该如何构建通过 std::allocator<T>::allocate()
分配的对象?我找到了 std::uninitialized_fill()
和 std::uninitialized_copy()
,但据我所知,它们不是分配器感知的,并且它们会进行复制,我认为这会对非 POD 类型的性能造成很大影响。
看起来 construct
的 static
形式仍然存在于 C++20 中。也许那是为了取代 construct
?
https://en.cppreference.com/w/cpp/memory/allocator_traits/construct
我在自定义分配方面做得并不多,所以我没有使用这些函数的个人经验,但他们可能更喜欢静态函数以打破依赖关系似乎是合理的。
还有一个construct_at
函数是C++20新增的
您可以使用 std::allocator_traits
。
删除 construct 方法的关键是因为分配器特征已经有了该方法,而 STL 容器仍然使用 std::allocator_traits::construct
。
这是一个小例子:(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);