【问题标题】:Extend std::vector to move elements from other vector type扩展 std::vector 以从其他向量类型移动元素
【发布时间】:2013-03-13 21:03:23
【问题描述】:

假设我有一个非 STL 向量类型,它通过 operator std::vector<T> 与 std::vector 兼容。是否可以将其元素 移动 到 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);
    }
}

【问题讨论】:

  • 你想要一个 move_iterator 在那里。
  • 并且您需要 C++11 *this 引用机制,以便您可以重载 *this 是左值还是右值。

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


【解决方案1】:

我认为您需要对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 也没有。 :(

【讨论】:

  • 非常有趣,我确信 C++11 会以某种方式解决这个问题 :) 猜猜我会等到它得到更广泛的支持。
【解决方案2】:

最简单的做法(特别是如果您没有 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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 2012-12-12
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    相关资源
    最近更新 更多