2

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?

Helixirr
  • 911
  • 9
  • 18

2 Answers2

5

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.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • Did you mean this : `const int *bar(const int &a) { return &a; }`? That is UB, since `bar(1)` would create a temporary. – BЈовић Jan 31 '13 at 12:14
  • @BЈовић: I did mean that (although I've since renamed the function `baz`). `baz(1)` by itself is not UB, but it would be UB to dereference the resulting pointer after the end of the full-expression containing `baz(1)`. The issue in both cases (extracting a pointer from a const lvalue and extracting an lvalue from an rvalue reference) is that it's the caller's problem to figure out when the return starts to dangle. – Steve Jessop Jan 31 '13 at 12:16
  • btw `std::move(a)` rips guts out of `a`, making any access to it UB, therefore accessing it through a lvalue referenc is also UB – BЈовић Jan 31 '13 at 12:16
  • 1
    @BЈовић: that's not correct, `std::move(a)` does not rip the guts out of `a`. It merely provides an rvalue reference to `a` which *can* be used to rip the guts out of `a`, if you pass it to a function that actually does (for example) a move construction or move assignment. – Steve Jessop Jan 31 '13 at 12:18
  • @BЈовић Like Steve said (unfortunately `std::move` is a bit misnamed, not moving at all) and even then it wouldn't be UB to access `a`. A moved-from value is a perfectly valid object in a perfectly valid (yet undefined) state. So only accessing `a` after an **actual** move operation **and** that access requiring `a` to be in a certain state **and** `a` not being in that state would be UB. This is a common misunderstanding about move semantics. For example it's absolutely no problem to call `size` or `clear` on a moved-from `std::vector`, **even** if moving doesn't guarantee emptying. – Christian Rau Jan 31 '13 at 12:38
  • I was aware of this implicit conversion from rvalue to lvalue. "If it has a name, it's an lvalue." I wasn't sure about the lifetime, though, hence I asked the question in the first place. – Helixirr Jan 31 '13 at 16:52
  • @Helixirr: "If it has a name, it's an lvalue" -- I don't think that's a very useful maxim. The object is the thing that has the name, but it's an *expression*, not an object, which is categorized either an lvalue or an rvalue. So your slogan equates things that aren't the same. There can be objects without names that are referred to by lvalues, and there can be objects with names that are referred to by non-lvalue expressions. What you can say is that if it has a name, and that name is not an rvalue reference variable, then the name is an lvalue expression. – Steve Jessop Jan 31 '13 at 22:13
  • @Steve Jessop - I can under what you mean, but I try to avoid doing something like this for readability anyway: f() = 15; – Helixirr Feb 01 '13 at 06:40
  • @Helixirr: in practice operator overloads are the biggest source of assignments via references returned from function calls. `*it = 15; vec[15] = 15;`. I agree that `f() = 15;` is unusual. – Steve Jessop Feb 02 '13 at 08:48
  • @Steve Jessop - Yes, something like this: (std::string("Your current OpenGL version is too old (") + __to_string(__version_major) + '.' + __to_string(__version_minor) + ").\nWith an OpenGL version as old as yours, you\nare unable to use graphical features this application\nrequires.\n\nPlease upgrade your OpenGL version to at\nleast version 3.0. Upgrading can be\naccomplished by, for example, updating\nyour graphics drivers.\n\nProgram will now exit.").c_str() – Helixirr Feb 06 '13 at 21:13
1

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.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135