Will `std::vector` do anything I haven't asked it to

85 views Asked by At

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

There are 3 answers

0
Michael Burr On BEST ANSWER

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

0
Mark On

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.

0
AudioBubble On

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.