【发布时间】: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