Use the swap method to forcibly release memory occupied by STL containers

Source: Internet
Author: User

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/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.