简体   繁体   中英

Proper way to delete and free up memory of a vector (prevent different memory related errors) in c++

creating a vector:

std::vector<int> pqrs;

delete in proper way to free up all memory (prevent memory leaks and other memory related issues) inside the function:

pqrs.clear();
std::vector<int>().swap(pqrs);

My question is: both clear and swap required (say for calling destructor)? or swap is sufficient for all purpose.

In case of std::vector<int> you don't need to do either clear() nor swap to free memory, because elements of std::vector<int> here ( int s) are automtically allocated and freed by the std::vector<int> methods anddestructor. Data will be freed at the end of scope (function or program).

Hence,answer to your question would be, You don't need to call clear or swap .

Since vector<int> object in above question is a variable with automatic storage - so it will be automatically destroyed when it goes out of scope. And when a container object goes out of scope, it's destructor is called which in-turn frees up space used for storage of contained elements and during this step destructor for all contained elements also gets invoked (in case of user-defined types). So, if we have just plan int elements, no need to do anything extra. But we would have memory leak if contained type if T* where T is some user-defined type because in that case destructor wouldn't be called explicitly for pointed-to objects.

Your phrase about memory leaks makes the whole meaning of the question unclear. When the vector goes out of scope, the memory is released. There should be no memory leak.

In major projects, it is fairly common to need a vector to release its allocation at a certain point before it goes out of scope. Failure to do so is not a memory leak but may be a problem. For that purpose, .clear() is useless. The swap approach you suggested (without the .clear ) works. I don't know a way to do it without swap .

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