If you are referencing a constant, the compiler first establishes a temporary variable, and then the value of that constant is placed in a temporary variable, and the action on that reference is the operation on that temporary variable. A C + + constant reference can be initialized with any other reference, but it cannot be changed.
There are two points worth noting about the initialization of references:
(1) When the initial value is an lvalue (can get address), there is no problem;
(2) When the initial value is not an lvalue, only one const t& (constant reference) can be assigned. And there is a process for this assignment:
First, the value is implicitly converted to type T, and then the result is stored in a temporary object, which is then initialized with the temporary object to initialize the reference variable.
Returns a local object from a function through a C + + constant reference:
It is not common to return a reference to a local object from a function:
1 void ) 2{ 3 t t; 4 return t; 5 // The T-Object T got destroyed here and the returned reference is not valid anymore .
Special case: Returns a common reference
Const void ) { T t; return t; } Const T & my_t_obj = My_op ();
In this case, the local variable t will not be destroyed directly, but will remain until the end of the My_t_obj life cycle.
In summary, a C + + constant Reference syntax can reference a temporary variable. This method makes sense when using references as function arguments and returning local variables. For the time being, the constant reference is used primarily as a function parameter or as a guarantee that the original variable is not modified.
General use of a reference to a constant (reference to const) (reproduced)