在使用不同分配器的两个 std::vector 之间移动元素

问题描述 投票:0回答:1

我有一个类型为

std::vector<a_trivially_copiable_type, my_custom_allocator>
的对象。在某些时候,我需要将其注入到仅接受
std::vector<a_trivially_copiable_type>
的第三方库中。对于我的用例来说,从那时起
my_custom_allocator
将不再被使用是很好的。不好的是,
std::vector
内容在此过程中随时会重复。

所以我尝试这样做:

auto tmp = std::vector<a_trivially_copiable_type>{};
tmp = std::move(the_vector_with_the_custom_allocator);
auto library_obj = ThirdPartyLibraryObject{std::move(tmp)};

但这不起作用,因为 STL 要求两个

std::vector
具有完全相同的类型。另外,
std::move
中的
<algorithm>
也没有帮助,因为它只会移动
a_trivially_copiable_type
类型的对象,这不会导致比
std::memcpy
更好的结果,因为它们是可复制的。

有没有办法实现这个目标?

c++ vector move allocator
1个回答
0
投票

不好的是 std::vector 内容在进程中随时重复。

为了避免这种情况,您从根本上必须确保

std::allocator
在内存中的分配方式使得
std::allocator::deallocate
(默认用于
std::vector
)能够释放它。如果您想将对象移动到新的分配,那么您要求做的就是复制所有对象(因为它们是可简单复制的)。

不幸的是,实现此目的的唯一方法是确保分配器返回的内存使用从

std::allocator::allocate
获得的内存。由于如果您使用自定义分配器,您可能不打算这样做,因此您尝试做的事情是不可能的。

© www.soinside.com 2019 - 2024. All rights reserved.