2

I know that when using push_back() on a vector, it is possible that that vector will be re-allocated (if there is no space left) to have more space. When using pop_back(), can the vector be re-allocated, in order to free unused space?

In general, can I somehow ensure my vector is not re-allocated (assuming I know its max capacity), when using a sequence of push_back() and pop_back() operations? This re-allocation invalidates my pointers and iterators and causes problems.

Yahav
  • 211
  • 3
  • 4

2 Answers2

5

When using pop_back(), can the vector be re-allocated, in order to free unused space?

pop_back will not reallocate. You have to explicitly call shrink_to_fit.

In general, can I somehow ensure my vector is not re-allocated (assuming I know its max capacity), when using a sequence of push_back() and pop_back() operations?

You should call reserve with the max capacity before pushing or popping anything.


What follows is more opinion-based:

This re-allocation invalidates my pointers and iterators and causes problems.

This is a code smell to me.

  • Having a bunch of pointers/iterators leads to code that is hard to understand and maintain (this exact scenario is a good example)
  • Even if you "fix" this by reserveing, you are now building in an assumption that could change in the future
  • vector may not be the right structure in the first place if you need these kinds of iterator stability guarantees
0x5453
  • 12,753
  • 1
  • 32
  • 61
  • Perhaps you can at least as a quick fix encapsulate/enhance vector in your own class, where you e.g. check, whether a push_back() would overflow the reserved capacity or check whether the memory location of the first element changes – Sebastian Jun 18 '20 at 06:27
4

To quote from cppreference:

Iterators and references to the last element, as well as the end() iterator, are invalidated.

So no reallocation is taking place, since, by inference, all other iterators remain valid. So, if you reserve the maximum amount of space you need up-front, then you should be able to get the behaviour you want.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48