现在,引用 TestRef.r 的地址就是 TestRef 对象的地址。因为 r 是 TestRef 的第一个成员。
您可以通过更新 TestRef.r 内存中的值存储来重新分配引用。
下面的代码显示您可以获取引用的地址,并且您可以将引用重新分配给差异变量。注意: 我的操作系统是 X64操作系统(我使用 Xcode MacBook Pro 2015,MacOs 10.15.1)。
#include <iostream>
using namespace std;
struct TestRef{
int& r;
int i;
TestRef(int& ref): r(ref){}
};
int main(int argc, const char * argv[]) {
int i = 10;
int j = 11;
TestRef r(i); // r.r is reference to i
cout << r.r << " " << i << " " << j << endl; // Output: 10 10 11
int64_t* p = (int64_t*)&r; // int32_t in 32 bit OS;
// Note:
// p is the address of TestRef r and also the address of the reference r.r
// *p is the address of i variable
//
// Difficult to understand? r.r indeed a pointer to i variable
// *p will return the address inside the memory of r.r
// that is the address of i variable
// this statement is true: *p == &i
// ------>
// now we change the value of *p to the address of j
// then r.r will be the reference of j instead the reference of i
*p = (int64_t)&j; // int32_t in 32 bit OS;
cout << r.r << " " << i << " " << j << endl; // Output: 11 10 11
return 0;
}