Reputation: 1067
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.
Upvotes: 0
Views: 114
Reputation: 605
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.
Upvotes: 1
Reputation: 1174
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
.
Upvotes: 2
Reputation: 5321
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
.
Upvotes: 0