Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping a vector with a copy of itself

Tags:

c++

vector

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?

like image 724
Dmitriy Kachko Avatar asked Feb 21 '12 15:02

Dmitriy Kachko


2 Answers

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().

like image 59
David Rodríguez - dribeas Avatar answered Oct 02 '22 12:10

David Rodríguez - dribeas


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.

like image 44
ereOn Avatar answered Oct 02 '22 14:10

ereOn