80

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?

Enlico
  • 12,203
  • 5
  • 28
  • 59
towi
  • 20,210
  • 25
  • 94
  • 167

5 Answers5

61

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_);}
    ...
};
Howard Hinnant
  • 179,402
  • 46
  • 391
  • 527
  • 5
    An excellent example. The pattern is, you *want* client code to *move* something -- allowing him to "steal". Yes, of course. – towi Apr 24 '11 at 14:38
  • Last time I checked, it was undefined to access after moving from. – Puppy Apr 26 '11 at 14:46
  • 4
    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 Apr 26 '11 at 17:07
  • 3
    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. – Howard Hinnant Apr 26 '11 at 17:08
  • 3
    Wouldn't it be safer to use `value_type` instead of `value_type&&` as the return type? – fredoverflow May 15 '11 at 12:33
  • 1
    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 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 May 15 '11 at 13:39
  • 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. – Howard Hinnant May 15 '11 at 16:21
  • 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) – Dave Abrahams Nov 30 '11 at 10:58
  • 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. – Potatoswatter May 15 '13 at 09:24
  • Is this valid if `*i_` is `const`? Just asking. – ThomasMcLeod Aug 04 '15 at 01:06
  • @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. – Howard Hinnant Aug 04 '15 at 03:48
  • Wouldn't this best be used with an r-value ref qualifier? – Emile Cormier Mar 27 '16 at 01:21
  • @EmileCormier: No. The purpose of `move_iterator` is to turn generic "copy" algorithms into "move" algorithms. See http://www.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. – Howard Hinnant Mar 27 '16 at 01:35
  • @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. – Emile Cormier Mar 28 '16 at 16:33
17

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.

Aaron McDaid
  • 24,484
  • 9
  • 56
  • 82
Clinton
  • 20,364
  • 13
  • 59
  • 142
  • 1
    While it's possible, this is generally frowned upon because this approach has its own issues besides saving temporaries. See http://stackoverflow.com/questions/6006527 – sellibitze May 25 '11 at 11:24
  • 2
    Don't those return calls need to use std::move()? – wjl Jun 10 '11 at 16:12
  • 1
    @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. – Clinton Jun 11 '11 at 06:27
  • 1
    @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. – M.M Mar 30 '15 at 02:20
  • @Clinton, I've added in the `move`s. Matt is correct. I've tested it – Aaron McDaid Jul 11 '15 at 19:31
  • 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&& x = vec1 + {1,2,3};`. The second argument will bind to the parameter `vector&& x2`, however this temporary only lasts for the full-expression it was created in, leaving `x` dangling. – M.M Jul 28 '15 at 00:04
  • 1
    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. – M.M Jul 28 '15 at 00:06
  • for `vector&& x2`, don't you want `x1 += std::move(x2);`? – TemplateRex Sep 14 '15 at 09:05
7

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).

Puppy
  • 138,897
  • 33
  • 232
  • 446
  • 5
    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 Apr 24 '11 at 11:43
1

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.

hangyuan
  • 111
  • 6
0

One more possible case: when you need to unpack a tuple and pass the values to a function.

It could be useful in this case, if you're not sure about copy-elision.

Such an example:

template<typename ... Args>
class store_args{
    public:
        std::tuple<Args...> args;

        template<typename Functor, size_t ... Indices>
        decltype(auto) apply_helper(Functor &&f, std::integer_sequence<size_t, Indices...>&&){
            return std::move(f(std::forward<Args>(std::get<Indices>(args))...));
        }

        template<typename Functor>
        auto apply(Functor &&f){
            return apply_helper(std::move(f), std::make_index_sequence<sizeof...(Args)>{});
        }
};

pretty rare case unless you're writing some form of std::bind or std::thread replacement though.

RamblingMad
  • 4,946
  • 1
  • 20
  • 41