More C++ Idioms/Clear-and-minimize

From Wikibooks, open books for an open world
< More C++ Idioms
Jump to navigation Jump to search

Clear-and-minimize
[edit]

Intent[edit]

Clear a container and minimize the capacity of the container.

Also Known As[edit]

This is sometimes called the swap with temporary idiom.

Motivation[edit]

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[edit]

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

std::vector<int> v;
//... Lots of push_backs and then lots of removes on v.
std::vector<int>().swap (v);

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

Solution in C++11[edit]

Since C++11, some containers declare the function shrink_to_fit(), like vector, deque and basic_string. shrink_to_fit() 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.

Known Uses[edit]

Related Idioms[edit]

References[edit]