Reputation: 28892
If I call std::vector::reserve
to reserve a certain amount of memory for my vector, will this memory remain allocated until I destroy my vector
or are there any method calls (perhaps clear
) that will free my reserved memory?
Edit: I will be reusing the container a large number of times so for performance reason I want to avoid memory allocations. It is for this reason I reserve memory up front so I want to be certain I do nothing to lose the allocated memory.
Upvotes: 1
Views: 137
Reputation: 24412
Edit: I will be reusing the container a large number of times so for performance reason I want to avoid memory allocations. It is for this reason I reserve memory up front so I want to be certain I do nothing to lose the allocated memory.
You need only to avoid two things:
1. shrink_to_fit, but it is only a request to free memory, it is not a must for vector to actually do this.
2.
Only swap
with empty vector will change capacity for sure (see See ideone):
vector<int> v;
v.reserve(100);
vector<int>().swap(v);
ASSERT(v.capacity() == 0);
Neither pop_back, clear nor resize to smaller size will reduce vector capacity.
BTW, consider to use std::array<>.
Upvotes: 1
Reputation: 7919
clear
only affects the size, not the capacity. shrink_to_fit
in C++11 may be what you are looking for.
Upvotes: 3