mistergreen
mistergreen

Reputation: 109

Does C++ pointer to an element of a vector become invalid when vector is growing?

When a vector is growing, then larger memory space is allocated where the whole vector collection is copied.

Does any pointer to an element of the vector become invalid after this memory move ?

Upvotes: 0

Views: 493

Answers (2)

Does C++ pointer to an element of a vector become invalid when vector is growing?

Yes of course, and that is documented. A pointer is a machine address, and when a block of memory is moved (your underlying <vector> implementation is likely to do some memcpy or memmove or their equivalent to move a block) the pointer to it becomes invalid. Remember that new is nearly a malloc followed by the call of the constructor. You could also look at the implementation code of ::operator new if using an open source implementation of C++

And you could also look at the preprocessor output of g++ -H -C -E sample-vector-code.cc if you use GCC (since its standard C++ library is free software, that you are allowed to study). The <vector> header expands to about 10KLOC of C++ code. Glancing into that with a good editor (like emacs) takes a dozen of minutes. Implementation details matters, even if you code above some abstraction.

Upvotes: 3

ShadowRanger
ShadowRanger

Reputation: 155497

Of course it becomes invalid. If the memory had to be moved (which isn't always, since library authors could cheat with realloc-like implementations that don't always result in a new allocation, especially when shrinking), then the memory is at a different address. Pointers aren't magic; they can't redirect to the logically equivalent memory on their own.

Upvotes: 2

Related Questions