user2370139
user2370139

Reputation: 1305

Can reallocation happen to a vector before the size reaches the reserved capacity?

Suppose I do v.reserve(1000000); Am I guaranteed no reallocation will happen before the first time v.size() is equal to 1000000 ?

Upvotes: 1

Views: 58

Answers (3)

Baum mit Augen
Baum mit Augen

Reputation: 50063

There will be no reallocation.

It would not be legal because inserting into a vector with sufficient capacity does not invalidate iterators (other than the end iterator) and references into said vector.

Upvotes: 2

There shouldn't be any new allocations if you don't reach the reserved size.

However you can read this interesting article about standard library 'optimizations' for your memory.

Upvotes: 0

Hafnernuss
Hafnernuss

Reputation: 2827

From 1:

If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).

In all other cases, the function call does not cause a reallocation and the vector capacity is not affected.

where n is the argument of elements to reserve size for.

Upvotes: 0

Related Questions