According to the C++ standard, is std::vector<T>::pop_back()
ever allowed to reduce the capacity of the vector?
I am asking because I would like to have a guarantee, that the following code will not throw an out of memory exception:
my_vec.pop_back();
if (...)
my_vec.push_back(...);
Assume that my_vec
is an std::vector<int>
.
I guess there are three possibilities:
Yes, this can happen according to both C++03 and C++11.
No, C++11 prohibits this (but C++03 does not).
No, both C++03 and C++11 prohibits this.
Yes, my question is related to Does std::vector.pop_back() change vector's capacity?, but my question is specifically about what the standard guarantees.
Note also that the accepted answer in Does std::vector.pop_back() change vector's capacity? is mostly about how to reduce the capacity of a vector, not about when it is guaranteed not to happen, and offers no evidence for its claim about pop_back().
The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.
No. That's implied by the fact that iterators, pointers and references prior to the point of erase remain valid. Reducing the capacity would require a reallocation.
C++ pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1. 1.
push_back effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call.
According to http://en.cppreference.com/w/cpp/container/vector/pop_back
No iterators or references except for
back()
andend()
are invalidated.
Therefore it may not reallocate. There is no C++11
tag on that page, which implies this is also true in 03. I will dig up the section references and edit them in for completeness.
Edit: Even better: From C++03
: [lib.container.requirements] (23.1), paragraph 10:
no
erase()
,pop_back()
orpop_front()
function throws an exception.
Same wording at 23.2.1/10 in N3337 (~C++11
).
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