In C++11, it is common practice to pass an lvalue into a function by reference.
int& f(int& a){
return a;
}
int main(void){
auto a = 1;
auto b = f(a);
return 0;
}
However, is it possible to have a value passed into a function by rvalue reference and return this value by lvalue?
int& f(int&& a){
return a;
}
int main(void){
auto b = f(1);
return 0;
}
Why is it or why isn’t it possible?
It’s possible, but normally unwise. This code is OK:
This code is OK too:
This code has undefined behavior:
So, it’s quite easy to misuse the function
foo.As for the reason it works — all that’s happening here is an implicit conversion from an rvalue reference to an lvalue reference. It would be inconvenient if that were not permitted, because it would mean for example that you could not write:
There might be stronger reasons for permitting the implicit conversion. I don’t know the official motivation, this is just the first I thought of.
Even in C++03 there was a related issue. You can write:
in order to take a pointer to a temporary/value — something that the language prevents you doing directly and which leads to the same undefined behavior if the return value outlives the expression in which it is produced.
You could say that forbidding
&1(taking a pointer to a literal or other temporary) is one place in which the C++ standard doesn’t just assume the programmer knows what they’re doing. But I think historically the reasoning behind it is that you have to be able to take a const reference to a temporary in order for operator overloading to work. You don’t have to be able to take a pointer to a temporary, and C forbids it because in C an integer literal never needs to have a memory location. So C++ continues to forbid it, even though in C++ when you do take a reference to an integer literal then the compiler may be forced to create an actual location containing that value. Stroustrup probably could have said the same about taking a pointer to an integer literal, but there was no need.