I am having a hard time understanding lvalue and rvalue references. Look at this code example
#include <iostream>
//Returns r-value
int Add(int x, int y) {
return x + y;
}
//Return l-value
int & Transform(int &x) {
x *= x;
return x;
}
void Print(int &x) {
std::cout << "Print(int&) L value ref" << std::endl;
}
void Print(const int &x) {
std::cout << "Print(const int&) const l value ref" << std::endl;
}
void Print(int &&x) {
std::cout << "Print(int &&) r value ref" << std::endl;
}
int main() {
//x is lvalue
int x = 10;
//ref is l-value reference
int &ref = x ;
//Transform returns an l-value
int &ref2 = Transform(x) ;
//Binds to function that accepts l-value reference
Print(x);
Print(ref);
Print(ref2);
//rv is r-value reference
int &&rv = 8 ;
//Add returns a temporary (r-value)
int &&rv2 = Add(3,5) ;
//Binds to function that accepts a temporary, i.e. r-value reference
Print(3);
Print(rv);
Print(rv2);
return 0;
}
When I run this I got
Print(int&) L value ref
Print(int&) L value ref
Print(int&) L value ref
Print(int &&) r value ref
Print(int&) L value ref
Print(int&) L value ref
I can (I guess) understand the first 4. However for the last two I am printing rv and rv2 which I thought were r-values so why are they being passed to the Lvalue ref function?
rvandrv2are actually l-values, because they have names assigned to them. They both have r-value reference as their type.The 1st
Print()takes a const-reference, which can bind to both lvalues and rvalues. To call the 2ndPrint()instead, you will have to usestd::move()to convertrvandrv2into r-values, eg:Online Demo