Is there any case where a return of a RValue Reference (&&) is useful?

15,830

Solution 1

There are a few occasions when it is appropriate, but they are relatively rare. The case comes up in one example when you want to allow the client to move from a data member. For example:

template <class Iter>
class move_iterator
{
private:
    Iter i_;
public:
    ...
    value_type&& operator*() const {return std::move(*i_);}
    ...
};

Solution 2

This follows up on towi's comment. You never want to return references to local variables. But you might have this:

vector<N> operator+(const vector<N>& x1, const vector<N>& x2) { vector<N> x3 = x1; x3 += x2; return x3; }
vector<N>&& operator+(const vector<N>& x1, vector<N>&& x2)    { x2 += x1; return std::move(x2); }
vector<N>&& operator+(vector<N>&& x1, const vector<N>& x2)    { x1 += x2; return std::move(x1); }
vector<N>&& operator+(vector<N>&& x1, vector<N>&& x2)         { x1 += x2; return std::move(x1); }

This should prevent any copies (and possible allocations) in all cases except where both parameters are lvalues.

Solution 3

No. Just return the value. Returning references in general is not at all dangerous- it's returning references to local variables which is dangerous. Returning an rvalue reference, however, is pretty worthless in almost all situations (I guess if you were writing std::move or something).

Solution 4

You can return by reference if you are sure the referenced object will not go out of scope after the function exits, e.g. it's a global object's reference, or member function returning reference to class fields, etc.

This returning reference rule is just same to both lvalue and rvalue reference. The difference is how you want to use the returned reference. As I can see, returning by rvalue reference is rare. If you have function:

Type&& func();

You won't like such code:

Type&& ref_a = func();

because it effectively defines ref_a as Type& since named rvalue reference is an lvalue, and no actual move will be performed here. It's quite like:

const Type& ref_a = func();

except that the actual ref_a is a non-const lvalue reference.

And it's also not very useful even you directly pass func() to another function which takes a Type&& argument because it's still a named reference inside that function.

void anotherFunc(Type&& t) {
  // t is a named reference
}
anotherFunc(func());

The relationship of func( ) and anotherFunc( ) is more like an "authorization" that func() agrees anotherFunc( ) might take ownership of (or you can say "steal") the returned object from func( ). But this agreement is very loose. A non-const lvalue reference can still be "stolen" by callers. Actually functions are rarely defined to take rvalue reference arguments. The most common case is that "anotherFunc" is a class name and anotherFunc( ) is actually a move constructor.

Share:
15,830

Related videos on Youtube

towi
Author by

towi

Programmer, Algorithmicist, Programming Languagcist, Pythonist, C++icist, Photographer, Boardgamer.

Updated on November 04, 2020

Comments

  • towi
    towi over 3 years

    Is there a reason when a function should return a RValue Reference? A technique, or trick, or an idiom or pattern?

    MyClass&& func( ... );
    

    I am aware of the danger of returning references in general, but sometimes we do it anyway, don't we? T& T::operator=(T) is just one idiomatic example. But how about T&& func(...)? Is there any general place where we would gain from doing that? Probably different when one writes library or API code, compared to just client code?

  • towi
    towi about 13 years
    I think during the early design of the C++0x there was a time when it was suggested that things like the move-assign and T&& operator+(const T&,T&&) should return a &&. But that is gone now, in the final draft. That's why I ask.
  • towi
    towi about 13 years
    An excellent example. The pattern is, you want client code to move something -- allowing him to "steal". Yes, of course.
  • Puppy
    Puppy about 13 years
    Last time I checked, it was undefined to access after moving from.
  • Howard Hinnant
    Howard Hinnant about 13 years
    In general a moved from object, when used in the std::lib, must meet all of the requirements specified for whatever part of the std::lib it is using. std-defined types must additionally guarantee that their moved from state is valid. Clients can call any function with that object as long as there are no pre-conditions on its value for said function-call.
  • Howard Hinnant
    Howard Hinnant about 13 years
    Finally, in the example above, there are no moved-from objects. std::move doesn't move. It only casts to rvalue. It is up to the client to move (or not) from that rvalue. That client will only access a moved-from value if he dereferences the move_iterator twice, without intervening iterator traversal.
  • fredoverflow
    fredoverflow about 13 years
    Wouldn't it be safer to use value_type instead of value_type&& as the return type?
  • Howard Hinnant
    Howard Hinnant about 13 years
    Yes, I think so. However in this case I think the added benefit outweighs the risk. move_iterator is often used in generic code to turn a copying algorithm into a moving one (e.g. a move-version of vector::insert). If you then supply a type with an expensive copy & move to the generic code, you've got an extra copy gratuitously added. I'm thinking array<int, N> for example. When move-inserting a bunch of these into vector, you don't want to accidentally introduce an extra copy. On the risk side, const X& x = *i is pretty rare. I don't think I've ever seen it.
  • Howard Hinnant
    Howard Hinnant about 13 years
    On second thought, no, it wouldn't be safer. Rationale: The danger in returning a reference is that if the reference refers to a temporary, then the temporary can destruct before the reference does, thus leading to a dangling reference. In this example the reference will (almost always) refer to an lvalue. Very few iterators return prvalues, and those that do should probably not be adapted by move_iterator. So in the normal use case, even if the client holds the reference beyond the sequence point, the referred-to object still exists after the sequence point.
  • sellibitze
    sellibitze about 13 years
    While it's possible, this is generally frowned upon because this approach has its own issues besides saving temporaries. See stackoverflow.com/questions/6006527
  • wjl
    wjl almost 13 years
    Don't those return calls need to use std::move()?
  • Clinton
    Clinton almost 13 years
    @wjl: Good question, but I don't think so. std::move works without using std::move. I think the cast to && does the trick here.
  • Dave Abrahams
    Dave Abrahams over 12 years
    Well, it's still a wee bit safer to return a value, you have to admit. However, that makes the move eager as opposed to optional (depending on what the client of operator* does with it)
  • Potatoswatter
    Potatoswatter about 11 years
    Returning by value or rvalue reference aren't comparable in risk, because they do completely different things. Returning by RR is exactly the same as adding std::move around the function call, that's all. And since it only makes sense to move an lvalue, use-cases of prvalues are just another story.
  • M.M
    M.M about 9 years
    @Clinton there's no cast in your code, you have to return std::move(x2); etc. Or you could write a cast to rvalue reference type, but that's just what move does anyway.
  • Aaron McDaid
    Aaron McDaid almost 9 years
    @Clinton, I've added in the moves. Matt is correct. I've tested it
  • M.M
    M.M almost 9 years
    This code is a bad idea (not sure how I overlooked that in my previous comment) because it may return a dangling reference. For example, say you do vector<N>&& x = vec1 + {1,2,3};. The second argument will bind to the parameter vector<N>&& x2, however this temporary only lasts for the full-expression it was created in, leaving x dangling.
  • M.M
    M.M almost 9 years
    The code is only correct if the return value is either unused, or assigned to an object -- but then you may as well have returned by value and taken the arguments by value and let copy elision do its thing.
  • ThomasMcLeod
    ThomasMcLeod almost 9 years
    Is this valid if *i_ is const? Just asking.
  • Howard Hinnant
    Howard Hinnant almost 9 years
    @ThomasMcLeod: If value_type is also const, it is valid, but there will be no moving, just a copy. If value_type is not const, then you'll get a compile-time error complaining about assigning a const value to a non-const reference.
  • TemplateRex
    TemplateRex over 8 years
    for vector<N>&& x2, don't you want x1 += std::move(x2);?
  • Emile Cormier
    Emile Cormier about 8 years
    Wouldn't this best be used with an r-value ref qualifier?
  • Howard Hinnant
    Howard Hinnant about 8 years
    @EmileCormier: No. The purpose of move_iterator is to turn generic "copy" algorithms into "move" algorithms. See open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1771.html and search for "replace_copy". replace_copy + move_iterator allows you to build replace_move for yourself. But the replace_copy algorithm need do nothing special. It is ignorant of the fact that it is dealing with move_iterator. It dereferences this iterator just as it would any other.
  • Emile Cormier
    Emile Cormier about 8 years
    @HowardHinnant, sorry I had tunnel vision when I posted that comment. I was only looking at the operator* line and didn't pay attention to the move_iterator class around it.