OP запросил изменение ссылочного объекта путем назначения ссылки, и ему очень правильно сказали, что это изменило ссылочный объект, а не ссылку.Теперь я сделал более острую попытку действительно изменить ссылку и нашел потенциально неприятные вещи.Сначала код.Он пытается переназначить ссылку на новый созданный объект, затем изменяет ссылку, то есть ссылочный объект, обнаруживает, что это не отражено в явно ссылочных объектах, и приходит к выводу, что в C ++ может быть случай висячего указателя.Извините за наспех составленный код.
using namespace std;
vector<int>myints;
auto &i = myints.emplace_back(); // allocate and reference new int in vector
auto myintsaddr = &myints; auto myintfrontaddr = &myints.front(); // for future reference
i = 1; // assign a value to the new int through reference
cout << hex << "address of i: 0x" << &i << " equals " << "address of
myints.back(): 0x" << &myints.back() << '.' << endl; // check reference as expected
i = myints.emplace_back(); // allocate new int in vector and assign to old reference variable
i = 2; // give another value to i
cout << "i=" << i << ", myints={" << myints[0] << ", "<< myints[1] << '}' << endl; // any change to potentially referenced objects?
cout << hex << "&i: 0x" << &i << " unequal to " << "&myints.back(): 0x" << &myints.back() << " as well as &myints.front(): 0x" << &myints.front() << endl;
cout << "Myints " << (myintsaddr== &myints?"not ":"") << "relocated from " << myintsaddr << " to " << &myints << endl;
cout << "Myints front() " << (myintfrontaddr == &myints.front() ? "not " : "") << "relocated from " << myintfrontaddr << " to " << &myints.front() << endl;
Вывод:
address of i: 0x0063C1A0 equals address of myints.back(): 0x0063C1A0.
i=2, myints={1, 0}
&i: 0x0063C1A0 unequal to &myints.back(): 0x0063F00C as well as &myints.front(): 0x0063F008
Myints not relocated from 0039FE48 to 0039FE48
Myints front() relocated from 0063C1A0 to 0063F008
Вывод: по крайней мере, в моем случае (VS2017) ссылка сохранила в памяти точно такой же адрес, носсылочные значения (часть вектора) были перераспределены в другом месте.Ссылка, я могу быть болтался.