I am looking at code from Microsoft and I noticed the following:
An optional parameter std::vector<T>* vOut
is passed into a function.
The function itself uses a separate local std::vector<T> result
for the optional result.
At the end of the function, they do the following to pass the result to the caller:
if(vOut) {
std::swap(*vOut,result);
}
why would someone use a std::swap
here instead of a move-assignment like
*vOut = std::move(result)
?
Well, there is always the possibility that something was made pre-C++11, so moves might not have been available.
However, I might occasionally use swap
when I want the other object to be in a "better defined" state -- that is, move the data but also have a clear object, instead of just one that's merely safe to use.
And, last but not least, somebody might not think about every tiny detail -- not every piece of production code is meant as a textbook example, and std::move
vs. std::swap
, in many cases, is micro-optimization at best (the move might even be implemented on top of a swap
member), so it's not something to be particularly concerned about.