Question

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?

Was it helpful?

Solution

It's possible, but normally unwise. This code is OK:

#include <utility>
#include <iostream>

int &foo(int &&a) {
    return a;
}

int main() {
    int a = 1;
    std::cout << foo(std::move(a)) << "\n";
}

This code is OK too:

int main() {
    std::cout << foo(1) << "\n";
}

This code has undefined behavior:

int main() {
    int &a = foo(1); // lifetime of the temporary 1 ends "at the semi-colon"
    std::cout << a << "\n";
}

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:

void bar1(const int &a) {
    std::cout << (a + 1) << "\n";
}

void bar2(int &&a) {
    bar1(a);
    ... do destructive stuff with a ...
}

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:

const int *baz(const int &a) { return &a; }

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.

OTHER TIPS

If you take ownership, you are responsible for the object. If you don't save it somewhere, it's like returning a reference to temporary; when the function scope ends, the object you "owned" is destroyed, and so the returned reference ceases to be valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top