I wrote a simple program below for the explain.
class A{
public:
int *x;
A(){ x = 0; }
~A(){ delete x; }
void foo(){
x = new int();
*x = 99;
}
};
int main(){
std::vector<A> as;
for (int i = 0; i < 3; ++i){
as.push_back(A());
as.back().foo();
}
return 0;
}
I expect that as contains 3 instance of A.
But the pointer x of the first element lose its reference(written dummy value) after second push_back is called, and an exception is thrown at 3rd iteration.
This is resolved adding as.reserve(3) before for loop.
Why this happened?