Let's say I have an object:
struct Foo { int bar_; Foo(int bar) bar_(bar) {} };
and I have an STL container containing Foo s, possibly a vector, and I take
// Elsewhere... vector<Foo> vec; vec.push_back(Foo(4)); int *p = &(vec[0].bar_)
This is a terrible idea, isn't it?
The reason is that vector will store its elements in a dynamically allocated array somewhere, and ultimately, if you add enough elements, it will have to select another array, copy all the elements of the original array, and delete the old array. After that, p points to garbage. This is why many vector operations will invalidate iterators.
It would seem reasonable to assume that the operation, which will invalidate the iterators from the container, will also invalidate the pointers to the data elements of the container elements, and that if the operation does not invalidate the iterators, these pointers will still be safe. However, many reasonable assumptions are false . Is this one of them?
source share