Comparison between C ++ reference and pointer References are a concept in C ++. Beginners can easily confuse references with pointers. ClickProgramN is a reference of M, and M is a referent ). Int m; Int & n = m; N is equivalent to M alias (nickname). Any operation on N is an operation on M. Therefore, n is neither a copy of M nor a pointer to M. In fact, n is m itself. Reference rules: (1) The reference must be initialized at the same time (the pointer can be initialized at any time ). (2) there cannot be a null reference, and the reference must be associated with a valid storage unit (the pointer can be null ). (3) once the reference is initialized, the reference relationship cannot be changed (the pointer can change the object at any time ). In the following example, K is initialized as a reference of I. Statement K = J cannot be changed to a reference of J, but the value of K is changed to 6. Since K is an I reference, the I value is also changed to 6. Int I = 5; Int J = 6; Int & K = I; K = J; // The values of K and I are changed to 6; The main function of the reference is to pass the parameters and return values of the function. In C ++, function parameters and return values are transmitted in three ways: value transfer, pointer transfer, and reference transfer. The following is a sample program for "value transfer. Since X in the func1 function is a copy of the external variable N, changing the value of X does not affect N, so the value of N is still 0. Void func1 (int x) { X = x + 10; } ... Int n = 0; Func1 (N ); Cout <"n =" <n <Endl; // n = 0 The following is an example program of "pointer passing. Since X in the func2 function is a pointer to the external variable N, changing the content of this pointer will change the value of N, so the value of N is 10. Void func2 (int * X) { (* X) = (* x) + 10; } ... Int n = 0; Func2 (& N ); Cout <"n =" <n <Endl; // n = 10 The following is a sample program for "reference transfer. Since X in the func3 function is a reference of the external variable n, x and n are the same thing, changing X is equal to changing N, so the value of N is 10. Void func3 (Int & X) { X = x + 10; } ... Int n = 0; Func3 (N ); Cout <"n =" <n <Endl; // n = 10 Comparing the above three examples, we will find that the nature of "reference transfer" is like "pointer transfer", while the writing method is like "value transfer ". In fact, "Reference" can do anything "Pointer" can also do. Why do we need to "Reference" this? The answer is "Use appropriate tools for proper work ". Pointers can operate anything in the memory without any constraints. Although pointers are powerful, they are very dangerous. If you only need to borrow the "alias" of an object, use "Reference" instead of "Pointer" to avoid exceptions. |