Question

In C++, if I initialize a std::vector v(100); and never try to resize() nor reserve() it, is the capacity() guaranteed to stay the same all the time? I want to make sure that no memory alloc/freeing/realloc/etc is going on for perforance reasons. (Yes, it would affect performance; my functions are called all the time, and they must returrn quickly).

Resuming it all:

std::vector<float> v;
// somehow, `v' is initialized to have 100 elements
void f() { // this function must return _very_ quickly
    /* do some processing, without ever calling v.resize() or v.reserve(), but
       accesing v.size() and v[i] all the time */
    /* it is guaranteed that no system calls (such as memory management)
       will take place here? */
} // no objects on the stack whose destroyers might try to `delete' anything.
Was it helpful?

Solution

From the remarks on vector::reserve() in C++11 23.3.6.3 "vector capacity":

It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

OTHER TIPS

There is vector::data() exposing the array allocated. Hence it is fair to assume that any operation on the vector equivalent to any modification on vector::data() will not effect memory allocation.

Any non-const operation on the vector might modify it. Any O(n) operation (like push_back) on the vector may cause the underlying data to be relocated. You can click into the various pages on cppreference to see what the big-Oh notation is for the operations you intend to use.

Calls to size and the subscript operator must complete in O(1) time, and so the vector would not reallocate its buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top