Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 496
towi Avatar asked Apr 24 '11 11:04

towi


People also ask

Can a function return rvalue reference?

Typically rvalues are temporary objects that exist on the stack as the result of a function call or other operation. Returning a value from a function will turn that value into an rvalue. Once you call return on an object, the name of the object does not exist anymore (it goes out of scope), so it becomes an rvalue.

Can a function return a reference C++?

A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.

What is the point of an rvalue reference?

Rvalue references is a small technical extension to the C++ language. Rvalue references allow programmers to avoid logically unnecessary copying and to provide perfect forwarding functions. They are primarily meant to aid in the design of higer performance and more robust libraries.

How do you pass rvalue reference to a function?

If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.


2 Answers

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_);}     ... }; 
like image 122
Howard Hinnant Avatar answered Sep 20 '22 19:09

Howard Hinnant


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.

like image 33
Clinton Avatar answered Sep 17 '22 19:09

Clinton