From my interpretation of the standard, it appears that you should be guaranteed that no reallocation will occur if you have already called reserve and are using push_back and pop_back only.
I believe this is the case because it guarantees that once reserve is called, no reallocation will occur on insertion until the size needs to surpass the capacity. It also states that pop_back is the same as a call to erase on the last element, and erase only invalidates iterators and references after the element that is erased. Put those together and I think it's guaranteed that you can pop_back safely.
Thanks, Daved. That's what I suspected, but what Stroustrup said confused me. I think he was just talking about calling resize() exclusively. But I still don't understand why using resize() to REDUCE the size should be capable of causing a reallocation, if the capacity doesn't change (or can it?).
Originally Posted by Daved
I was hoping that since the swap trick is a common idiom (and at present the simplest way of doing what it does), the compiler would recognize what it's being asked to do, and avoid actually creating the temporary, instead just copying the contents of v to wherever it wants to (possibly shrinking it in place).
Originally Posted by anon
Edit: And if it's not smart enough, that's a really good argument for a vector member function that does this, to make it clear.
>> That's what I suspected, but what Stroustrup said confused me.
I agree, what he says is confusing. My guess is that there is no guarantee either way for resize()-ing smaller, so to be safe he added the (or fewer) part. You could always ask him, he tends to answer emails, although maybe a search of comp.lang.c++.moderated might be better first.
>> possibly shrinking it in place
The problem is that shrinking the memory is difficult. I understand what you are hoping for, but I think you have to just bite the bullet and either leave unused capacity or allow copying of the elements.
In STL the allocation of memory for a container is decoupled from the implementation of the container itself. If you need more control over how allocation happens, you need to learn about and write a custom allocator.
Originally Posted by robatino
However, if the vector itself doesn't release the memory, it won't really matter what the allocator does. The allocator only allocates or deallocates when the vector says to, and in this case the problem is that the vector is not releasing the memory when you want to shrink it.
I guess it is possible that you could come up with other workarounds via a custom allocator, but only if the situations were right.