C++ reference bottom

The underlying reference is the pointer constant.
     At the high-level language level, the relationship between the pointer constant and the reference variable is as follows:

  1. In the memory, they occupy 4 bytes (32-bit system) of space. They must be initialized at the time of definition, and the pointed object or the referenced object cannot be modified. The pointer constant stores the address of the pointed object, reference The address of the referenced object is also stored in the variable.
  2. The pointer constant itself allows addressing; the reference variable itself is not allowed to be addressed , and the address operation of the reference variable will return the address of the object referenced by the reference variable. (The address of the reference variable is controlled by the compiler, and the programmer cannot directly access it).
  3. Any code that uses a reference variable can be converted into a corresponding form of code that uses a pointer constant. Conversely, code that uses pointer constants may not necessarily be implemented with reference variables. For example, an array of pointer constants cannot be changed to an array of reference variables. In fact, you cannot create an array of references at all.
#include <iostream>
using namespace std;

/*
 * 证明引用是变量(指针常量),需要分配内存。虽然无法在高级语言层面更改引用所指向的变量,但是可以
 * 通过特殊手段,找到引用变量的地址,并修改其指向的对象。
 * 编译环境:VS2015 Debug x86
 */
int main() {
    
    
	int i = 4;
	int j = 5;
	int &ri = i;

	void *pi, *pj;

	pi = &i;
	pj = &j;

	cout << "[addr] i=0x" << pi << endl;
	cout << "[addr] j=0x" << pj << endl;

	int dis = int(pi) - int(pj);
	cout << "[dis] dis=" << dis << endl; // 变量i和变量j之间地址的差值

	int *addr = reinterpret_cast<int*>(int(pj) - dis); // 计算引用ri的地址

	*addr -= dis; // 令引用ri指向j

	ri = 45;

	cout << i << j << endl; // 输出:4 45

	getchar();
}

Guess you like

Origin blog.csdn.net/weixin_40315481/article/details/107995412