While reading code I see that:
vector<TypeA>(typeAObj).swap(typeAObj);
My question is
Why do they swap a vector with a copy of itself?
That's a pattern for shrink-to-fit in C++03, where there is no such operation in the interface of the vector class. What the code does is creating a copy (hopefully the capacity
of the vector will be close to the number of available elements) and then swaps it with the original vector. After the expression completes, the temporary (which now holds the original buffers) is discarded and the memory is released.
Consider:
std::vector<int> large;
large.reserve( 10000000 ); // might be the result of multiple push_back/erase
// large.capacity() >= 10000000
large.push_back( 1 ); // Make more explicit that 'large' might not be empty
std::vector<int>( large ).swap( large );
// large.capacity() is hopefully closer to 1
In C++11 the vector type has been modified to provide a shrink_to_fit
operation that takes on that role. It is important to note that neither the old pattern nor shrink_to_fit
are binding operations, that is, there is no guarantee on the capacity
of the vector after the operation other than capacity() >= size()
.
I believe it is a way to "shrink" the vector to a minimal size.
vector<TypeA>(typeAObj)
creates a copy of the vector whose reserved size may be smaller than the original.
So swapping a vector with a fresh copy of itself could be a way of freeing some undesired memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With