Search code examples
c++vector

Can std::vector::resize() change the vector's capacity, or cause memory reallocation, if resizing is always within the initial capacity?


Can std::vector::resize() change the vector's capacity(), or cause memory reallocation, if resizing is always within the initial capacity?

Here is my use case:

#include <vector>
const uint64_t maxSize = /* some large size */;
// SimpleCStruct is a fixed size C-struct containing as members basic C types and other
//     fixed size C-structs
std::vector<SimpleCStruct> v;
v.reserve(maxSize);
SimpleCStruct * const dataPtr = v.data(); // has to be saved before the loop below begins
for( /* very large number of iterations*/ )
{
    const uint64_t numberOfElementsWritten = C_function_writes_data_to(dataPtr);
    v.resize(numberOfElementsWritten);
    // numberOfElementsWritten < maxSize (always)
    // 'v' is serialized to disk here
}

v.data() provides direct access to the underlying contiguous storage and so calling a C-level function on it is expected to work correctly.

The documentation says:

Vector capacity is never reduced when resizing to smaller size.

However, in my use case, some resizes will increase and some will decrease the vector's size (while always staying within the capacity).


Solution

  • constexpr void resize(size_type sz);

    Effects: If sz < size(), erases the last size() - sz elements from the sequence. Otherwise, appends sz - size() default-inserted elements to the sequence.

    constexpr iterator erase(const_iterator position); constexpr iterator erase(const_iterator first, const_iterator last);

    Effects: Invalidates iterators and references at or after the point of the erase.

    From that point, iterators and references before the point of the erase are not invalidated. Hence, memory reallocation does not happen and the vector capacity is not changed.