I'm new to C++ so this may be a newbie question however I'm not entirely clear how to clear it from memory. I've searched online and looked are several answers but was unclear on how to properly execute what im trying to do.
How can i clear my vector from memory correctly in c++? Thanks and i apologize if this is a dup post.
vector<ElementData> Elements;
As mentioned by a comment below, i would like to return the memory used as well.
except that it will not return any memory to the system as the capacity remains unchanged.
The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
std::vector variables are normally destructed automatically when you go out of scope, or when the class object they are members of are destroyed. The destructor of std::vector also destroys all elements in the vector.
To completely clear a vector explicitly, first clear the vector (destroy the elements)
v.clear()
then return the memory previously reserved for the vector elements
v.shrink_to_fit();
http://en.cppreference.com/w/cpp/container/vector/shrink_to_fit
Only call shrink_to_fit
if it's likely that the vector previously contained far more elements than you are going to fill it with.
If you want to reset you vector back to a empty state then we can use the swap
trick to swap the contents of the vector into a temporary that will get destroyed and free the memory
vector<ElementData> Elements
// fill the vector up
vector<ElementData>().swap(Elements);
This will create a temporary empty vector, swap it with the one you have so now it is empty and then destroy everything in the temporary vector.
You can see it working in this little example
int main() {
std::vector<int> foo(500);
std::cout << foo.capacity() << std::endl;
std::vector<int>().swap(foo);
std::cout << foo.capacity() << std::endl;
}
Live Example
When your program ends, vector
's dtor will get called and delete your vector for you, since you've allocated it on the stack. Furthermore, the dtor for ElementData
will get called for each one in the vector.
In most cases, the best way is to limit the scope of the vector to where it's actually needed. So, instead of something like:
vector<Elements> Elements;
... do some work with Elements ...
Elements.clear(); // or whatever "trick" you want to use
... do more work where Elements is not needed ...
You would do this:
{ // begin a new scope
vector<Elements> Elements;
... do some work with Elements ...
} // Elements is now out of scope, its memory has been freed
... do more work where Elements is not needed ...
The other benefit of this is that after Elements
has gone out of scope, you can't accidentally reuse it. If the function is small, you probably don't need to create a new explicit scope. Returning from the function will have the same effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With