I know that C++ STL vector relocated the twice allocated space when pushback exceeds the capacity. My question is that if I have a reference to a vector, will it stay valid after pushbacks?
An example is following :
void displayVector(vector<int>& p)
{
for(auto i:p)
cout<<i<<" ";
cout<<endl;
cout<<"capacity = "<<p.capacity()<<endl<<endl;
}
int main()
{
vector<int> x(1);
vector<int>& y=x;
cout<<"x"<<endl;
displayVector(x);
cout<<"y"<<endl;
displayVector(y);
for(int i=0;i<100;i++)
x.push_back(10); // re- allocation takes place many times
cout<<"x"<<endl;
displayVector(x);
cout<<"y"<<endl;
displayVector(y);
}
Results that I got from above program showed that y
remains valid as a reference to x
even after many re-allocations.
So my questions are:
1) Will it always happen or this might break in some case?
2) How does reference remain valid in the cases where it remains valid, i.e. what happens under the hood to keep the reference valid even after re-allocations.