I have a class that has a vector member variable, which I fill up as follows:
class Foo {
vector<int> v;
void g() {
vector<int> w;
// fill w
v = w;
}
};
My question: the temporary vector w can grow to be huge and I don’t want to pay the price
of copy construction. Should I be using std::swap instead of copy here? My understanding
is that std::swap will be more efficient due to specialization for vector (where it
will just swap pointers to the heap).
Yes, you should swap here. In C++11, you can also say
v = std::move(w);.Either way, the variable
wis going out of scope immediately, so its contents don’t matter, and you might as well transfer ownership instead of copying.