Search code examples
c++c++11move-semanticsrvalue-reference

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


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?


Solution

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