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

towi picture towi · Apr 24, 2011 · Viewed 15k times · Source

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?

Answer

Howard Hinnant picture Howard Hinnant · Apr 24, 2011

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_);}
    ...
};