(1) The difference between pointers and references

Qualitative difference

  • The pointer itself is a variable, which stores the address, and the declared type name only explains how to interpret the location pointed to by the pointer.
  • Reference is a product of C++. The underlying implementation is actually a pointer, but the implementation looks like an alias (more like a pointer constant, and feels like overloading some operators, such as dereference (*)), which causes Made a few differences.

The difference in use:

  1. The reference must be initialized and cannot be NULL, and the pointer can be NULL. And the value of the pointer can be changed, the reference cannot be changed (more like const, the concept of constant pointer)
  2. There are const pointers, but no const references
  3. The pointer can have multiple levels (** p), and the reference has only one level
  4. "sizeof reference" obtains the size of the pointed variable (object), and "sizeof pointer" obtains the size of the pointer itself; (the pointer also needs to be dereferenced, and the reference directly shields the process and directly takes out the content)
  5. The increment (++) operation meaning of pointer and reference is different; (address++, value++)
  6. If you return objects or memory allocated by dynamic memory, you must use pointers, and references may cause memory leaks.

The difference when passed as a function parameter:

  1. Using pointers to pass parameters can achieve the purpose of changing the actual parameters, because what is passed is the address of the actual parameter, so using *a actually takes the data in the memory unit storing the actual parameter, that is, the actual parameter Change, so you can achieve the goal, when the reference is passed as a parameter, a copy of the actual parameter is also passed to the formal parameter.
  2. When passing a reference as a function parameter, what is actually passed is the actual parameter itself, that is, what is passed in is not a copy of the actual parameter, so the modification of the formal parameter is actually a modification of the actual parameter, so the parameter is used by reference When transferring, not only save time, but also save space.

Guess you like

Origin blog.csdn.net/qq_40329851/article/details/114273762