1

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.

Hamidreza Soleimani
  • 2,504
  • 16
  • 19
Pranay
  • 39
  • 3

1 Answers1

2

Your y reference to x will always remain the same (and valid), no matter what happens internally in x. Because that's what happen when x has to reallocate memory due to pushbacks exceeding capacity, the internal pointer to allocated memory has to change as more sequential (hence located at a different place) memory is needed.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54