简体   繁体   中英

Why doesn't std::vector::resize() deallocate the memory when you want to reduce the size of the vector?

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?

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM