C++11 rvalue reference and constant lvalue reference save the underlying analysis of temporary variables (function return value)

Rvalue references save temporary variables (function return values)

: Temporary variables are rvalues

1. Ordinary variable receiving function return value:
Insert picture description here
2. Rvalue reference variable receiving function return value:
Insert picture description here
3. Using const int& and rvalue reference is the same effect, only const int& cannot modify this temporary variable.
Insert picture description here
4. Use int& just No, this is an lvalue reference, it will prompt that the type is incorrect:
error: invalid initialization of non-const reference of
type'int &' from an rvalue of type'int ' int& constRef = add(x);Insert picture description here

in conclusion:

Whether it is an rvalue reference or an ordinary variable to save the return value, it is finally saved through eax (register) when the function returns.

The difference is:
1. Ordinary variable: just assign eax to the ordinary variable directly 2. Rvalue
reference: just put the value of eax in another location (temporary variable), and then assign the address of this location to the rvalue reference .
3. Constant lvalue reference: It has the same effect as rvalue reference, but the temporary variable cannot be modified by constant lvalue reference
(so the temporary variable of the function return value does not always exist, depending on what type is used when returning Variable to receive)

Guess you like

Origin blog.csdn.net/m0_37599645/article/details/112860603