Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense for a function to return an rvalue reference?

Tags:

c++

What would be a valid use case for a signature like this?:

T&& foo();

Or is the rvalue ref only intended for use as argument?

How would one use a function like this?

T&& t = foo(); // is this a thing? And when would t get destructed?
like image 731
Martin B. Avatar asked Sep 03 '25 10:09

Martin B.


1 Answers

For a free function it doesn't make much sense to return a rvalue reference. If it is a non-static local object then you never want to return a reference or pointer to it because it will be destroyed after the function returns. It can possibly make sense to return a rvalue reference to an object that you passed to the function though. It really depends on the use case for if it makes sense or not.

One thing that can greatly benefit from returning an rvalue reference is a member function of a temporary object. Lets say you have

class foo
{
    std::vector<int> bar;
public:
    foo(int n) : bar(n) {}
    std::vector<int>& get_vec() { return bar; }
};

If you do

auto vec = foo(10).get_vec();

you have to copy because get_vec returns an lvalue. If you instead use

class foo
{
    std::vector<int> bar;
public:
    foo(int n) : bar(n) {}
    std::vector<int>& get_vec() & { return bar; }
    std::vector<int>&& get_vec() && { return std::move(bar); }
};

Then vec would be able to move the vector returned by get_vec and you save yourself an expensive copy operation.

like image 102
NathanOliver Avatar answered Sep 05 '25 00:09

NathanOliver