views:

513

answers:

4

If I allocated an std::vector to a certain size and capacity using resize() and reserve() at the beginning of my program, is it possible that pop_back() may "break" the reserved capacity and cause reallocations?

+4  A: 

No. pop_back() will not shrink the capacity of vector. use std::vector<T>(v).swap(v) instead.

aJ
+11  A: 

No. The only way to change a vector's capacity is the swap trick

template< typename T, class Allocator >
void shrink_capacity(std::vector<T,Allocator>& v)
{
   std::vector<T,Allocator>(v.begin(),v.end()).swap(v);
}

and even that isn't guaranteed to work according to the standard. (Although it's hard to imagine an implementation where it wouldn't work.)

As far as I know, the next version of the C++ standard (what used to be C++0x, but now became C++1x) will have std::vector<>::shrink_to_fit().

sbi
Its still 0x. The x is a hex digit (so we still have 6 years to ratify it) :-)
Martin York
@Martin: I know that one, but it doesn't fly. For example, C++11 would be C++0xB. So C++0x would have to be changed to either C++1x or C++0xx. `:)`
sbi
+1  A: 

NO. Same as push_back , pop_back won't impact the capacity(). They just impact the size().

EDIT:

I should have said push_back won't change the capacity when the v.size() < v.capacity().

pierr
+1  A: 

pop_XXX will never change the capacity. push_XXX can change the capacity if you try to push more stuff on than the capacity allows.

Zanson