It seems that the C ++ (2003) standard implicitly guarantees that memory is not reallocated if you call the clear() or erase() method of std::vector .
In accordance with the requirements of the sequence (table 67) a.clear() equivalent to a.erase(begin(),end()) .
In addition, the standard states that the erase(...) member function of the std::vector<T> element does not throw an exception unless it is thrown by the copy constructor T (section 23.2.4.3). Therefore, this is implicitly guaranteed, since redistribution may cause an exception (sections 3.7.3, 20.4.1.1).
Also v.begin() remains unchanged, since erase(...) will invalidate all iterators after the delete point (section 23.2.4.3). However, this will not be dereferenced (since v.begin() == v.end() ).
So, if you have a standard compatible implementation, you're fine ...
CORRECTION
My reasoning is wrong. I managed to show that erase(...) does not redistribute, but the implementation can still free memory if you delete all the elements. However, if a.capacity() says βyou can add N elements without reallocating memoryβ after deleting / cleaning, you're fine.
The C ++ 11 standard defines a.clear() without reference to a.erase(...) . a.clear() not allowed to throw an exception. Consequently, it can be freed, but not redistributed. Therefore, you should check the capacity after cleaning the vector to make sure that the memory still exists and that the next resizing will not be redistributed.
source share