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?
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.
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.
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.
If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.
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_);} ... };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With