I read chapter 7 of C ++ primer 4 th and have a clear answer.
First, the function parameters.
If the parameter type is not reference, the parameter pushed by the function caller (called argument, the parameter of the function itself is called parameter, which is distinguished by the two) will be copied, it is then assigned to parameter. If unfortunately this parameter is a vector, the entire vector, including all the elements in it, will be copied. This is the copy of the parameter.
If the parameter type is of the reference type, the above parameter copy process will not exist.
Obviously, if there is a parameter copy action, modifications to parameter in the function will not affect argument. If no parameter copy is available, modifying the parameter will directly affect the argument
Second, the return value of the function.
There are also two cases. If the return value of a function is not of the reference type, the compiler automatically copies the return variable to a temporary object (temporary object) during return ), then the temporary object can be used by the function caller. In other words, if we return the local variable defined in a function, this is okay, because this variable will be copied to the temporary object. Even if the local variable itself disappears at the end of the function.
If the return value of a function is of the reference type, there is no such thing as a temporary object. What is return.
Therefore, based on the above two points, there are two very important inferences:
1. If the return value of a function is of the reference type, the reference of a local variable in the function cannot be returned because the local variable also disappears at the end of the function.
2. No matter whether the return value of the function is of the reference type or not, do not return a pointer to a local variable in the function. This pointer may be accessible by the function caller, but the object referred to by this pointer must not be accessible after the function is completed.