Re: when can vector::resize cause a reallocation?
On 24/06/11 08:26, Joshua Lehrer wrote:
Consider this code:
std::vector<int> v;
v.reserve(32);
v.resize(1);
After the reserve call the capacity should be at least 32. Can the
resize call cause a reallocation?
The standard says this about reserve():
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().
Does the resize call here count as an "insertion"? C++98 says that
resize(size_type sz, T c = T()) should act like insert(end(), sz-
size(), c); here. C++0x draft N3092 only says that resize(size_type
sz) should "append" a default constructed element to the vector.
also, what about this code:
std::vector<int> v;
v.reserve(32);
v.resize(31);
v.resize(1);
v.resize(0);
v.resize(32);
are there any reallocations allowed in the above code after the call
to reserve?
Thanks,
Joshua
Simply put, vector usually allocates memory for an array of size given
by reserve. As long as any resize does not exceed the current vector
capacity you should not experience any memory reallocation. Effectively
each time a resize is called, for increasing size new elements are
created using the default constructor, and for decreasing size the old
elements that are no longer needed have the destructor called.
Most implementations of vector use 3 pointers to type T, as follows:
The start address of the memory allocated
The address where the next element may be added
The start address + capacity, (end address), of the memory allocated
Hence if the next element address is the end address when trying to add
an element, then a reallocation would be required.
In short if you do not attempt to do an operation that would increase
the size of the vector >= vector capacity, then no reallocation is required.
HTH
cpp4ever
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]