So if I reserve(100) first, add some elements, and then resize(0) (or any other number smaller than the current size), will the vector reallocate memory to a take less space than 100 elements?
Asked
Active
Viewed 1,687 times
2 Answers
6
vector<T>::resize(0)
should not cause a reallocation or deletion of allocated memory, and for this reason in most cases is preferable to vector<T>::clear()
.
For more detail see answers to this question: std::vector resize downward

Community
- 1
- 1

George Skoptsov
- 3,831
- 1
- 26
- 44
-
4`clear` doesn't cause a reallocation either, so I don't see why it would be preferable... – ildjarn Apr 13 '12 at 01:39
-
I've seen at least one implementation where `clear` freed the memory. – Mark B Apr 13 '12 at 02:37
-
@MarkB: It shouldn't have. :P – GManNickG Apr 13 '12 at 02:48
-
@GManNickG While that's true (reference?) sometimes in programming you have to be pragmatic based on the tools you have access to/are forced to use. – Mark B Apr 13 '12 at 02:59
-
@MarkB: For sure, but when something deviates from the standard it's usually not worth worrying about because, when it *does* happen, you don't need to be told; it's a bug! Reference is actually in the linked question from this answer. The C++11 standard clarifies that only `shrink_to_fit()` should be expected to modify capacity, and even that's non-binding. – GManNickG Apr 13 '12 at 03:12
-
@GManNickG: I'm curious: where does C++11 state that `clear` shouldn't modify the capacity? – Nicol Bolas Apr 13 '12 at 03:35
-
6@NicolBolas: §23.3.6.3/6 says (cutting), "...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()`." Meaning you must be able to call `clear()` and then still be able to insert until the reserved limit is reached. (Also, `clear()` is defined in the 'generic' table 100 at §23.2.3 to only destroy elements, which means capacity is unchanged.) – GManNickG Apr 13 '12 at 04:06
-
Great comment, GMan! Maybe modify the answer to account for the standard clear() behavior? Also, about "preferable", it is very subjective :P In my case I wanted the exact behaviour of resize() - to not reallocate (and thus save time). – Cray Apr 13 '12 at 09:02
2
Doing a vector::resize(0)
or to a smaller count rather than current count should not deallocate any memory. However, it may destroy these elements.
For a reference on std::vector::resize
, take a look at std::vector::resize

josephthomas
- 3,256
- 15
- 20