Remi.b
Remi.b

Reputation: 18219

Will `resize` have any risk to reduce the vector capacity?

In C++, the method resize (of std::vector), changes the size of the vector (and construct / destroys object if necessary), reserve allows to eventually increase the capacity of a vector. shrink_to_fit will reduce the capacity of the vector to match its size. When increasing the vector size (either through resize, push_back or insert), the capacity will be increased if needed (it doubles every time it needs to increase if I am not mistaken).

Do the standards ensure that a vector will never reduce its capacity, unless the function shrink_to_fit is called? Or is it possible that a vector capacity will vary depending upon what the compiler think being wise to do?

Upvotes: 2

Views: 680

Answers (1)

Justin
Justin

Reputation: 25277

No, the vector's capacity will not be reduced by reserve or resize.

std::vector::reserve:

If new_cap is [not greater than capacity] ... no iterators or references are invalidated.

std::vector::resize

Vector capacity is never reduced when resizing to smaller size because that would invalidate all iterators, rather than only the ones that would be invalidated by the equivalent sequence of pop_back() calls.

Relevant part of the standard

Upvotes: 4

Related Questions