Containers such as vector, list, and set are used in the project. After running, the containers need to be cleared to release memory to reduce memory overhead.
At first, I used the clear () function to release the memory. Actually, the memory was not released.
As a reminder from colleagues, clear () cannot release the memory and needs to be released using swap. So I checked and found the following information:
Unlike deque, vector memory usage only increases and does not decrease. For example, if you first allocate 10,000 bytes and then erase drops the last 9,999, although there is only one valid element, the memory usage is still 10,000. All spaces are recycled during vector analysis.
Empty () is used to check whether the container is empty,Clear () can clear all elements. However, even if clear () is used, the occupied memory space remains the same. If you need dynamic space reduction, consider using deque. If you have to use vector, here is a method:
As mentioned in many articles on objective STL and C ++, clear () cannot guarantee memory reclaim. However, swap techniques are acceptable. The specific method is as follows:
Vector <int> Nums;
Nums. push_back (1); nums. push_back (1); nums. push_back (2); nums. push_back (2 );
Vector <int> (). Swap (Nums); // or nums. Swap (vector <int> ());
Vector <int> (). Swap (Nums); or add a pair of braces as shown below, which means the same:
{
STD: vector <int> TMP = Nums;
Nums. Swap (TMP );
}
Add a pair of braces to automatically analyze the structure of tmp when exiting {}.
The swap technique is to enable the vector to leave its own scope by switching the swap () function, thereby forcibly releasing the memory space occupied by the vector.
Http://cycloid.blog.163.com/blog/static/8847862009617711497/