Will the vector's memory be compromised?
Even if it does not leak, how can you reduce the space occupied?
We know that Vector has a clear () method?
Prototype:
#include <vector>void clear();
The function clear () deletes all elements stored in the vector. If the element of the vector is some object, it invokes their respective destructor (destructor) for each element that is currently stored. However, if a vector is stored as a pointer to an object, the function does not call the corresponding destructor. In the second case, in order to completely remove the elements in the vector, you should use a loop similar to the following:
std::vector<SomeObject*> aVector; //The elements of the vector are created with the operand ‘new‘ at some point in the program [...] for(int i=0 ; i<aVector.size() ; i++) delete aVector[i]; aVector.clear();
When clear is called, the vector's size (size) becomes zero. But its capacity (capacity) does not change, and the vector itself does not release any memory.
If you want to both empty the vector and release the vector's capacity, you can use the swap technique.
Doing so creates a temporary empty vector, which replaces the vector that you want to empty.
"The clear of the vector does not affect the capacity, you should swap an empty vector." ”
vector<type>(v).swap(v);
For a string it might look like this
String (s). Swap (s);
That is, creating a temporary copy is consistent with the original vector, and it is worth noting that at this point the copy is as small as possible to match the required data. The copy is immediately exchanged with the original vector v. Okay. At this point, after the swap is executed, the temporary variable is destroyed and the memory is freed. At this point, V is the original temporary copy, while the exchanged temporary copy is a very large vector (but has been destroyed)
To prove this, I wrote a program that reads as follows:
#include <iostream>#include <vector>using namespace STD; vector <string>VCharChintMain () { for(inti =0; i<1000000; i++) V.push_back ("Hello vector");Cin>> ch;//Check memory usage at this time to occupy 54MV.clear ();Cin>> ch;//Check again at this time, still occupy 54M cout<<"The capacity of the Vector is"<< v.capacity () << Endl;//At this time the capacity is 1048576 vector<string>(v). Swap (v);cout<<"The capacity of the Vector is"<< v.capacity () << Endl;//At this time the capacity is 0 Cin>> ch;//Check the memory, release the 10m+ is the data memory return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
No escaping pits--properly releasing the vector's memory