Clear a container and minimize the capacity of the container.
Also Known AsEdit
This is sometimes called the swap with temporary idiom.
Standard library containers often allocate more memory than the actual number of elements in them. Such a policy results in an optimization of saving some allocations when a container grows in size. On the other hand, when size of the container reduces, there is often leftover capacity in the container. The leftover capacity of the container can be unnecessary wastage of memory resources. clear-and-minimize idiom has been developed to clear a container and reduce the extra capacity to a minimum of zero and thereby saving memory resources.
Solution and Sample CodeEdit
Clear-and-minimize idiom is as simple as the one given below.
std::vector <int> v; //... Lots of push_backs and then lots of remove on v. std::vector<int>().swap (v);
The first half of the statement, std::vector<int>() creates a temporary vector of integers and it is guaranteed to allocate zero raw memory or an implementation minimum. The second half of the statement swaps the temporary vector with v using non-throwing swap idiom, which is efficient. After swapping, the temporary created by the compiler goes out of scope and the chunk of memory originally held by v is released.
Solution in C++0xEdit
In C++0x, some containers declare the function shrink_to_fit(), e.g. vector, deque, basic_string. shrink_to_fit() which is a non-binding request to reduce capacity() to size(). Thus, using clear() and shrink_to_fit() is a non-binding request to clear-and-minimize.
- Programming Languages — C++ draft standard.