Re: when can vector::resize cause a reallocation?
On 2011-06-24 09: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?
No.
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.
It counts as insertion, but it is unfortunate that the semantics of both
resize overloads are described differently (A new issue has been opened
to keep them in sync both the currently proposed wording suggests to use
the term "append" now in both places). Note that the usage of "append"
within the container description is quite common, e.g. the general
effects of push_back are described in Table 101 ? "Optional sequence
container operations" as "append". It would be nice, if this clause
would say somewhere: "Within this sub-clauses the term append is used
and means an insertion at the end of a sequence", but alas this does not
exist. I'm not sure that this is a real issue, because I have not found
yet an implementation where this was indeed misinterpreted (and what
would be the misinterpretation?). IMO this is more an editorial problem
than a real issue.
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?
No, because none of the resize() calls produces a size that exceeds the
capacity at this point. In fact, the capacity is never changed after the
call of reserve in this example code.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]