简体   繁体   中英

When/How do container data types (string, vector, etc.) in C++ free their dynamically allocated memory?

Since container data types have dynamic size I'm assuming they allocate memory on the heap. But when/how do they free this allocated memory?

They get freed either when they go out of scope (if the container was created in the stack), or when you explicitly call delete on the container(in case of heap-based container). When this happens, the destructor of the container automatically gets called and the heap memory allocated for the container (that contains the data) are freed then.

Simply removing an element in the container won't necessarily free the memory right away, since STL containers generally use caching to speed things up. Remember, new/delete operations are relatively costly.

They free the memory in their destructors when they are destroyed. (And they are destroyed by having delete or delete [] called if the container itself is heap allocated, or by going out of scope if it is stack allocated)

Short answer: When you remove elements from it.

Generally it happens when you remove element from the container blow its previous growth threshold. It's an implementation detail, but usually for example a vector creates an internal array of N T's.

When you insert more than N of T's, then the vector realocates it memory and grows to some multiple of N (again - implementation detail) to store the new elements, same happens with removal - when your remove elements from your vector it shrinks whenever it reaches the previous multiple of N... until you end up with only one multiple of N, or 0 if you clear it and shrink it with

The heap memory (node storage) is deleted also when the vector object is destructed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM