More C++ Idioms/Clear-and-minimize

= Clear-and-minimize =

Intent
Clear a container and minimize the capacity of the container.

Also Known As
This is sometimes called the swap with temporary idiom.

Motivation
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 the 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. The clear-and-minimize idiom has been developed to clear a container and reduce the extra capacity to a minimum of zero, thereby saving memory.

Solution and Sample Code
Implementing the Clear-and-minimize idiom is as simple as the one given below.

The first half of the statement,, creates a temporary   guaranteed to allocate either zero raw memory or an implementation minimum. The second half of the statement swaps the temporary with  using the 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  is released.

Solution in C++11
Since C++11, some containers declare the function, like vector, deque and basic_string. is a non-binding request to reduce  to. Thus, using  and   is a non-binding request to clear-and-minimize.

Related Idioms

 * Shrink-to-fit
 * Non-throwing swap