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

Moving elements between two std::vectors which are using different allocators

提问人:thebugger 提问时间:9/29/2023 更新时间:9/30/2023 访问量:68

问:

我有一个类型的对象。在某些时候,我需要将其注入到仅接受 .对于我的用例,从那时起将不再使用是可以的。不好的是,内容在此过程中随时都会重复。std::vector<a_trivially_copiable_type, my_custom_allocator>std::vector<a_trivially_copiable_type>my_custom_allocatorstd::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 要求两者具有完全相同的类型。此外,in 也无济于事,因为它只会移动 类型的对象,这将导致比 a 更好的结果,因为它们是可简单复制的。std::vectorstd::move<algorithm>a_trivially_copiable_typestd::memcpy

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

C++ 向量 移动 分配器

评论

1赞 Oersted 9/29/2023
这难道不是pmr容器/分配器的目的吗?
1赞 Ahmed AEK 9/29/2023
如果容器太大,你不能有 2 个副本,那么最好的选择是不使用矢量,而是使用高度碎片化的容器,你可以逐个复制和删除它。
1赞 Oersted 9/29/2023
哼,我可能对这部分想得不够多。我完全不确定是否可以用 .movepmrmove
1赞 thebugger 9/29/2023
@Oersted问题是 pmr 也将 std::vector 的类型更改为 std::p mr::vector
3赞 Sam Varshavchik 9/29/2023
不,没有办法实现这一点。

答: 暂无答案