Consider this snippet:
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();
}
If we assume that class X
implements move semantics, how can I efficiently implement MoveAppend
?
Just trying to improve slightly the answer of @Daniel: the function should not be defined twice, the source should be passed by value.
Now the caller can decide whether to copy or move.
Never use
&&
for arguments, unless you have to (for example: std::ifstream&&).Just do:
If
dst
is empty, a move-assignment fromsrc
todst
will do the job - that will be as cheap as it can be, just "stealing" the array encapsulated bysrc
so thatdst
will point to it afterwards.If
dst
is not empty, elements appended todst
will be move-constructed from elements insrc
. After the call tostd::move()
,src
will not be empty - it will contain "zombie" moved-from elements. That's why the call toclear()
is still necessary.I would slightly prefer this to the accepted answer:
Example: