Using C ++ vector memory - is it freed?

I know that vectors double in size when their capacity() exceeded. This operation takes some time, so the vectors must have an amortized constant time to add items using push_back() .

  • I am wondering what happens when a vector is compressed, so its size() less than half capacity() .

  • Do vectors ever provide the memory they use, or does it just disappear until the vector is destroyed?

It can be a lot of lost memory if they never decrease in size, but I never heard that they have this function.

+6
source share
5 answers

No, it is never released (i.e. capacity never decreases) until it is destroyed. The usual idiom for freeing memory is to create a new vector of the correct size and use this instead:

 std::vector<type>(originalVector).swap(originalVector); 

(inspired by "More Exceptional C ++", Item # 7)

+11
source

If you want your vector to use as little space as possible, you can say:

 std::vector<Foo>(my_vector).swap(my_vector); 

You can also call the member function shrink_to_fit() , but this is just an optional request.

+3
source

Erasing elements from a vector or even clearing an entire vector does not necessarily free up any memory associated with this element. This is due to the fact that the maximum size of a vector since its creation is a good estimate of the future size of the vector.

To use reduce idiom size :

 std::vector<int> v; //v is swapped with its temporary copy, which is capacity optimal std::vector<int>(v).swap(v); 

Solution in C ++ 0x

In C ++ 0x, some containers declare an idiom like the shrink_to_fit () function, for example. vector, deque, basic_string. shrink_to_fit () is an optional request to reduce the capacity () to size ().

0
source

They do not decrease.

In general, it is impractical to de-allocate memory.

For example, now the vector can shrink and then grow again. It would be unnecessary to free up additional memory (and copy all the elements in memory), only to redistribute it later.

If the vector is compressed, there is also a good chance that the vector will be reduced to empty and then destroyed. In this case, the release from compression loss will also be a waste of time.

It can also be a useful optimization for reusing a vector object to avoid highlighting / placing content. This would be destroyed by the introduction of exemption, as it is being reduced.

In principle, most of the time freeing up additional memory is not worth it. In those few cases where this is possible, you can specifically ask about the transaction.

0
source

The memory disappears until the vector is destroyed.

-1
source

Source: https://habr.com/ru/post/895762/


All Articles