简体   繁体   中英

What does the default allocator do when a std::vector is resized (via either reserve() or resize())?

What does the default allocator do when a std::vector is resized (via either reserve() or resize())?

  • The memory chunk internally used by the std::vector is actually resized.

  • A new memory chunk is allocated, data is moved (eg, std::move d) from the old memory chunk to the new one, and finally the old memory chunk is deallocated.

C++ allocators do not support anything like C's realloc . Whenever vector needs more memory, it has to allocate new storage, move from old to new, and deallocate the old.

Either way, realloc wouldn't suit vector . With typical allocators, realloc will only save you a heavy copy operation if you are shrinking its size, or in some cases growing by only a few bytes. vector doesn't ever shrink, and it only grows in very large steps.

Note that move support is a new behavior in C++ 2011. Previous versions will copy.

When a vector needs to grow, in any operation including resize/reserve, but also push_back, insert... A new memory block is obtained, and the elements in the old dynamic array are either copied or moved to the new location (if the type supports moving ). After this is completed, the old elements are destroyed and the old memory released.

Note that move has a specific meaning in the standard that differs from the intuitive meaning: management of the contents of the objects (rather than the objects) are passed from the original object to the new.

除了解释语义的其他答案外, reserveresize之间要考虑的重要区别是: reserve仅分配内存而不初始化它,而resize分配内存并默认初始化它。

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