问题描述
请考虑以下片段:
class X;
void MoveAppend(vector<X>& src, vector<X>& dst) {
dst.reserve(dst.size() + src.size());
for (const X& x : src) dst.push_back(x);
src.clear();
}
如果我们假设 class X
implements move语义,如何有效地实现 MoveAppend
?
If we assume that class X
implements move semantics, how can I efficiently implement MoveAppend
?
推荐答案
Just do:
#include <iterator>
#include <algorithm>
// ...
void MoveAppend(std::vector<X>& src, std::vector<X>& dst)
{
if (dst.empty())
{
dst = std::move(src);
}
else
{
dst.reserve(dst.size() + src.size());
std::move(std::begin(src), std::end(src), std::back_inserter(dst));
src.clear();
}
}
如果 dst
为空,从 src
到 dst
的移动作业将执行作业因为它可以,只是偷由 src
封装的数组,以便 dst
将指向它。
If dst
is empty, a move-assignment from src
to dst
will do the job - that will be as cheap as it can be, just "stealing" the array encapsulated by src
so that dst
will point to it afterwards.
如果 dst
不为空,则附加到 dst
将从 src
中的元素移动构造。调用 std :: move()
, src
不会为空 - 它将包含zombiemove-from元素。这就是为什么仍然需要调用 clear()
。
If dst
is not empty, elements appended to dst
will be move-constructed from elements in src
. After the call to std::move()
, src
will not be empty - it will contain "zombie" moved-from elements. That's why the call to clear()
is still necessary.
这篇关于如何使用c ++ 11移动语义将向量内容附加到另一个向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!