1

I don't understand why I have to use std::vector::swap() to deallocate the memory of a vector when I want to reduce its size.

Why would someone want to reduce the size of a vector and at the same time keep the rest of the unused memory allocated?

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
jsguy
  • 2,069
  • 1
  • 25
  • 36

2 Answers2

6

Reducing the capacity of a vector involves

  • allocating new storage
  • copying over the existing elements
  • deallocating old storage

None of this is for free. Really shrinking a vector has a cost associated to it, and it isn't clear that users should pay it by default.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • As an aside, even `shrink_to_fit()` is only a non-binding request. – Deduplicator Oct 17 '14 at 14:45
  • Somehow, I doubt the downvoter will ever get your note. Instead, I was notified. – Deduplicator Oct 17 '14 at 18:52
  • @Deduplicator Sorry about that. I should have guessed that might happen... Sometimes they come back to have a peek. If there's an obvious error, a down-vote can make me realise it. This time I can't see it. – juanchopanza Oct 17 '14 at 18:53
1

To answer your question why someone would want to reduce a vector without deallocating, here is another scenario I'm currently working on:

I need a continuous buffer whose size is not known a priori so I use a vector to build it up. I'm actually going to need this many many times (>100k) during the execution of the program and each time the buffer may be slightly different in size. I want to recycle this buffer so I don't incur the expensive reallocation every cycle. The first few cycles are quite expensive since they reallocate several times during all the push_backs. After the first 100 cycles though, the capacity of the vector has grown to size where it is big enough to hold what it needs thus, I'm no longer allocating and deallocating memory every cycle and I'm only using about as much memory as is needed (important when running with many threads and potentially bumping into the total system RAM).

David L.
  • 209
  • 2
  • 11