vector swap

hi,
I have some code with the following line and am trying to understand what that does.

std::vector<double>().swap(test);

where
std::vector<double> test;
My q? is what is the idea of () before swap(test)
It's a trick to clear the vector AND set the capacity to zero. If you just call test.clear() the capacity will not be changed.

std::vector<double>() creates a temporary object with size=0 and capacity=0, that will only exist on that line. When you swap the two vectors only the internal pointers, size and capacity members of the vector will be swapped inside the vectors, so a the speed of a swap does not depend on the number of elements in the vectors. test after this be an empty vector with capacity=0.

In C++11 shrink_to_fit() was added to do the same thing.
test.shrink_to_fit();

EDIT: Just so that you know. I have probably made some assumptions here about things that is not mandated by the standard.
Last edited on
thanks, that answers my query
Topic archived. No new replies allowed.