OP要求通过分配给参考来更改参考对象,并且非常正确地告知操作员更改了参考对象,而不是参考。现在,我进行了一次更猛烈的尝试来真正更改参考,并发现了可能令人讨厌的内容。首先是代码。它尝试将一个新创建的对象重新分配给该引用var,然后更改该引用的又称引用对象,发现该对象未在明显引用的对象中得到反映,并得出结论,在C ++中可能存在悬挂指针的情况。对不起,我们急忙编写代码。
using namespace std;
vector<int>myints;
auto &i = myints.emplace_back();
auto myintsaddr = &myints; auto myintfrontaddr = &myints.front();
i = 1;
cout << hex << "address of i: 0x" << &i << " equals " << "address of
myints.back(): 0x" << &myints.back() << '.' << endl;
i = myints.emplace_back();
i = 2;
cout << "i=" << i << ", myints={" << myints[0] << ", "<< myints[1] << '}' << endl;
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),引用在内存中保留了完全相同的地址,但是引用值(向量的一部分)已重新分配到其他位置。参考我可能会晃来晃去。
const int &cri = i
不允许?在哪一行你不能写?对我而言,编译器允许在任何位置插入此类行。除此之外,这是一个清晰简洁的答案!