扩展std :: vector以从其他矢量类型移动元素

时间:2013-03-24 09:29:51

标签: c++ c++11 move-semantics

假设我有一个与operator std::vector<T>的std :: vector兼容的非STL向量类型。是否可以其元素移动到std :: vector而不是默认的复制结构,以便

OtherVectorType<SomeClass> f()
{
    OtherVectorType<SomeClass> v;
    v.pushBack(SomeClass());
    v.pushBack(SomeClass());
    v.pushBack(SomeClass());
    return v;
}

std::vector<SomeClass> sv = f();
在创建std :: vector sv时,

会使用SomeClass的移动构造函数(3次)吗?

我想像

template<typename T>
std::vector<T>& operator= (std::vector<T>& self, OtherVectorType<T>&& from)
{
    [...]
}

但还没有找到任何有效的解决方案。


为了说明,这是定义std :: vector运算符的方式:

template<typename T> class OtherVectorType
{
    [...]

    operator std::vector<T>() const
    {
        if (!m_size)
            return std::vector<T>();

        return std::vector<T>(reinterpret_cast<T*>(m_pElements),
                              reinterpret_cast<T*>(m_pElements) + m_size);
    }
}

2 个答案:

答案 0 :(得分:5)

我认为你需要rvalue references for *this的支持。

operator std::vector<T>() const &; // copy your own type's data
operator std::vector<T>() &&;      // move it into the std::vector<T>

可悲的是,支持很少见,即使是GCC 4.8也没有支持。 :(

答案 1 :(得分:1)

最容易做的事情(特别是如果你没有rvalue-this)就是使用make_move_iterator,如下所示:

#include <deque>
#include <vector>
#include <memory>
#include <iterator>

typedef std::unique_ptr<int> SomeClass;
typedef std::deque<SomeClass> OtherVectorType;

OtherVectorType
f()
{
    OtherVectorType v;
    v.push_back(SomeClass(new int (1)));
    v.push_back(SomeClass(new int (2)));
    v.push_back(SomeClass(new int (3)));
    return v;
}

std::vector<SomeClass>
to_vector(OtherVectorType&& o)
{
    return std::vector<SomeClass>(std::make_move_iterator(o.begin()),
                                  std::make_move_iterator(o.end()));
}

int main()
{
    std::vector<SomeClass> v = to_vector(f());
}