lvalues references and rvalues references in C++ with Examples
Prerequisites: lvalue and rvalue in C++, References in C++
“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the ‘&’ before the name of the variable.
int a = 10; // Declaring lvalue reference int& lref = a; // Declaring rvalue reference int&& rref = 20;
Below is the implementation for lvalue and rvalue:
Explanation: The following code will print True as both the variable are pointing to the same memory location. b is just an alternative name to the memory assigned to the variable a. The reference declared in the above code is lvalue reference (i.e., referring to variable in the lvalue) similarly the references for the values can also be declared.
rvalue references have two properties that are useful:
- rvalue references extend the lifespan of the temporary object to which they are assigned.
- Non-const rvalue references allow you to modify the rvalue.
Important: lvalue references can be assigned with the rvalues but rvalue references cannot be assigned to the lvalue.
lref = 10 rref = 20 lref = 30 rref = 40
Uses of the lvalue references:
- lvalue references can be used to alias an existing object.
- They can also be used to implement pass-by-reference semantics.
a = 10 b = 20 a = 20 b = 10
Note: When the function return lvalue reference the expression becomes lvalue expression.
Uses of rvalue references:
- They are used in working with the move constructor and move assignment.
- cannot bind non-const lvalue reference of type ‘int&‘ to an rvalue of type ‘int’.
- cannot bind rvalue references of type ‘int&&‘ to lvalue of type ‘int’.