在具有不同分配器的向量之间进行转换 [英] Converting between vectors with different allocators

查看:53
本文介绍了在具有不同分配器的向量之间进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个简单的C ++ 11样式有状态分配器类型.给定

I have written a simple C++11 style stateful allocator type. Given

template<typename T> class my_allocator {
   // the usual stuff
};

template<typename T> using my_vector = std::vector<T, my_allocator<T>>;

my_vector<int> x;

std::vector<int> y = x; // error

使用默认分配器允许从 my_vector 转换为 std :: vector 的最佳方法是什么?GCC 4.7(最近的svn)说

What is the best way to allow conversions from a my_vector to a std::vector using the default allocator? GCC 4.7 (recent svn) says

错误:从'my_vector< int>转换为{aka std :: vector< int,my_allocator< int>>}}转换为非标量类型'std :: vector< int>'请求

很明显,这可以通过一个简单的转换函数来完成,例如

Obviously this could be done with, say, a simple conversion function such as

template<typename T> std::vector<T> to_std_vec(const my_vector<T>& v)  {
   return std::vector<T>(&v[0], &v[v.size()]);
   }

但是这看起来很不雅致.C ++ 11中有更好的解决方案吗?

but this seems pretty inelegant. Is there a better solution in C++11?

当然,在这种情况下,移动语义是正确的,但是我希望复制构造和赋值能够正常工作,而不会产生额外的干扰/键入.

Move semantics are right out in this situation, of course, but I'd like copy construction and assignment to work without extra noise/typing.

推荐答案

您不可能希望绕开明显的副本: std :: vector< int>y(x.begin(),x.end(); . y 中的元素将由 std :: allocator 分配,而元素在 x 中,您自己的分配器已分配了这些内存,并且这些销毁了这两个分配器,它们可能具有与 memory pointers 完全无关的概念!没有理由一个分配器使用的内存存储与另一分配器没有任何关系.

You cannot possibly hope to get around the obvious copy: std::vector<int> y(x.begin(), x.end();. The elements in y will be allocated by the std::allocator, while the elements in x were allocated, and will be destroyed, by your own allocator. The two allocators could have entirely unrelated notions of memory and pointers! There's no reason that the memory storage that's used by one allocator is in any way related to that of the other.

除了复制语义元素之外,您还能做什么?

What else then can you do but make a semantic element copy?

如果您不再希望使用旧容器,则应该执行移动

If you don't want the old container any more, you should do a move, though:

std::vector<int> y(std::make_move_iterator(x.begin()),
                   std::make_move_iterator(x.end()));

(如果 elements 有自己的分配器,这会有所帮助.当然,不适用于 int .)

(This will help in case the elements have their own allocator which agrees. Not for int, of course.)

更新:为了强调这一点,请注意, vector< T,Alloc> 的内部数据缓冲区不是 not 类型 T * ,而不是 Alloc :: pointer 类型.没有理由认为这是两个不同的分配器的相关类型.

Update: To reinforce the point, please note that the internal data buffer of a vector<T, Alloc> is not of type T*, but rather of type Alloc::pointer. There's no reason that those are related types for two distinct allocators.

这篇关于在具有不同分配器的向量之间进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆