Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a std::map is cleared is it ensured, that the memory is deallocated

If a std::vector vec is cleared with vec.clear() the allocated memory must not be deallocated immediately. The size of the vector will be zero, but the capacity will/can be unchanged.

This is a very beneficial behaviour, since one can clear a large vector and assign new values to it, without the need of an expensive memory de/allocation. Also the memory will be less de-fragmented.

One can enforce that with vec.shrink_to_fit() shrink_to_fit.

std::map has a clear function, but no shrink_to_fit. What happens to the needed memory to store the map after a clear?

cppreference.com states that map.clear() erases all elements from the container. After this call, size() returns zero.

like image 311
schorsch312 Avatar asked Oct 29 '25 08:10

schorsch312


1 Answers

One can enforce that with vec.shrink_to_fit() shrink_to_fit.

Actually, shrink_to_fit doesn't enforce deallocation of memory. It simply allows it. The implementation is allowed to not deallocate.

If a std::map is cleared is it ensured, that the memory is deallocated

No. The only case where standard containers are guaranteed to deallocate their memory is when they are destroyed.

Map doesn't have a concept of capacity that vector has, so it doesn't need shrink_to_fit. A map after clear is in same situation as a vector is after clear + shrink_to_fit: It doesn't need to have any memory allocated... but it is not prohibited to have it allocated either.

like image 164
eerorika Avatar answered Oct 30 '25 22:10

eerorika