Is that some kind of an optimization to avoid re-allocating the vector's memory block?..
Almost. It is an optimization to avoid re-allocating whatever memory blocks might be present in vector
's value_type
. That is, it is a global assumption that assignment can be more efficient than destruction followed by copy construction.
For example consider vector<string>
assignment, for two equal sized vector
s, and a bunch of equal sized string
s in each spot in the vector
:
v2 = v1;
All this operation has to do is memcpy
each string
. No allocations at all. Reducing allocations/deallocations is one of the most important optimizations that exist today.
However, all is not lost for your Struct
. What you want to do is instruct the vector
that you do not wish to assign your Struct
s, but instead destruct them, and then copy construct them from v1
. The syntax for doing this is:
v2.clear();
for (const auto& x : v1)
v2.push_back(x);
As noted in the comments below, you can also copy construct v1
, and then swap
with the copy. You either need to create a temporary local copy of v1
, or you need to use v1
on the "lhs" of member swap:
std::vector<Struct>(v1).swap(v2);
I personally find this hard to read. In C++11/14 I prefer this alternative which involves move assignment:
v2 = std::vector<Struct>(v1);
These alternatives are easier on the eyes. But the first alternative, using clear()
and push_back
is going to be the most efficient on average. This is because the first alternative is the only one that has a chance of reusing capacity()
in v2
. The other two always recreate new capacity()
in the copy of v1
and throw away v2
's existing capacity()
.