Let us consider the following c++ code
#include <iostream> #include <vector> class A { int x, y; public: A(int x, int y) : x(x), y(y){} friend std::ostream & operator << (std::ostream & os, const A & a){ os << a.x << " " << a.y; return os; } }; int main(){ std::vector<A> a; std::vector<const A*> b; for(int i = 0; i < 5; i++){ a.push_back(A(i, i + 1)); b.push_back(&a[i]); } while(!a.empty()){ a.pop_back(); } for(auto x : b) std::cout << *x << std::endl; return 0; } Using a debugger I noticed that after the first insertion is done to a the address of a[0] changes. Consequently, when I'm printing in the second for loop I get an unvalid reference to the first entry. Why does this happen?
Thanks for your help!
vectorhas to increase its capacity to hold more elements, it's possible (or maybe it always happens?) that new memory is allocated and all elements are copied to the new space. If you want to prevent this, usea.reserve(5);before adding elements.bpoint at elements inaand you then emptya, what is there for the elements inbto point at?