Why does shrink_to_fit (if the request is fulfilled) cause reallocation?

  allocation, c++, memory-management

Given a container v with v.size() == 3 and v.capacity() == 5, my understanding is that a call to v.shrink_to_fit() can be fulfilled and, if it is, it causes v.capacity() to become 3.

However, this comes at the cost of a reallocation.

Why? Isn’t it possible to free the unused memory without reallocating a chunk of memory for what remains?

Probably this question has its roots into how more primitive commands like new/delete and malloc/free work.

Source: Windows Questions C++

LEAVE A COMMENT