Basic knowledge
On the difference between references and pointers in C ++
Essence: References are aliases, pointers are addresses, specifically:
① From the perspective of the phenomenon, the pointer can change the value it points to at runtime, and once the reference is bound to an object, it will not change. This sentence can be understood as: a pointer can be reassigned to point to a different object. However, the reference always points to the object specified during initialization and cannot be changed later, but the content of the specified object can be changed.
② From the perspective of memory allocation, the program allocates a memory area for a pointer variable instead of a memory area for a reference, because the reference must be initialized when it is declared, thereby pointing to an existing object. A reference cannot point to a null value.
Note: The standard does not specify whether the reference takes up memory or how the reference is implemented.
③ From the perspective of compilation, the program adds pointers and references to the symbol table when compiling. The symbol table records the variable name and the address corresponding to the variable. The corresponding address value of the pointer variable on the symbol table is the address value of the pointer variable, and the corresponding address value of the reference on the symbol table is the address value of the reference object. The symbol table will not be changed after it is generated, so the pointer can change the object pointed to (the value in the pointer variable can be changed), and the reference object cannot be changed. This is the main reason why using pointers is not safe and using references safe. In a sense, references can be thought of as immutable pointers.
The fact that there is no reference to a null value means that the code using the reference is more efficient than the pointer. Because you don't need to test its validity before using a reference. Instead, pointers should always be tested to prevent them from being empty.
⑤ In theory, there is no limit to the number of levels of pointers, but references can only be one level. as follows:
int ** p1; // legal. Pointer to pointer
int * & p2; // legal. A reference to a pointer
int & * p3; // illegal. Pointer to reference is illegal
int && p4; // illegal. References to references are illegal
Note that the above reading is from left to right.