Does it make sense for a function to return an rvalue reference?Is returning by rvalue reference more efficient?What should main() return in C and C++?Advantages of using forwardClasses, Rvalues and Rvalue ReferencesImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionWhy should I use a pointer rather than the object itself?Does this rvalue signature pattern make sense?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviationsReturn value or rvalue reference?Rvalue and Lvalue Referencesrvalue reference or forwarding reference?

How to cope with regret and shame about not fully utilizing opportunities during PhD?

Are there any established rules for splitting books into parts, chapters, sections etc?

Magento 2: How to get type columns of table in sql?

Why is it harder to turn a motor/generator with shorted terminals?

Can I say: "When was your train leaving?" if the train leaves in the future?

Quote from Leibniz

Jesus' words on the Jews

High Memory Utilization in Juniper ACX2100

Why are solar panels kept tilted?

Conditional probability - sum of dice is even given that at least one is a five

Extracting sublists that contain similar elements

Could there be a material that inverts the colours seen through it?

When a land becomes a creature, is it untapped?

What information do scammers need to withdraw money from an account?

CPLD based Pierce oscillator

Jumping frame contents with beamer and pgfplots

How to distinguish PICTURE OF ME and PICTURE OF MINE in Chinese?

In books, how many dragons are there in present time?

What's tha name for when you write multiple voices on same staff? And are there any cons?

Why did the metro bus stop at each railway crossing, despite no warning indicating a train was coming?

Does SQL Server allow (make visible) DDL inside a transaction to the transaction prior to commit?

Find hamming distance between two Strings of equal length in Java

What to do if SUS scores contradict qualitative feedback?

Anabelian geometry ~ higher category theory



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


Is returning by rvalue reference more efficient?What should main() return in C and C++?Advantages of using forwardClasses, Rvalues and Rvalue ReferencesImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionWhy should I use a pointer rather than the object itself?Does this rvalue signature pattern make sense?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviationsReturn value or rvalue reference?Rvalue and Lvalue Referencesrvalue reference or forwarding reference?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








22















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?









share|improve this question



















  • 6





    std::move comes to mind. It certainly returns T&&. Edit : std::optional::value also has an T&& overload. Edit 2 : It also has a const T && overload, though I'll admit I don't understand the meaning.

    – François Andrieux
    May 2 at 19:32







  • 1





    @FrançoisAndrieux the std::get family of functions, too.

    – Brian
    May 2 at 19:34






  • 1





    See this answer.

    – lubgr
    May 2 at 19:37











  • Isn't that a forwarding reference?

    – user2357112
    May 3 at 1:52

















22















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?









share|improve this question



















  • 6





    std::move comes to mind. It certainly returns T&&. Edit : std::optional::value also has an T&& overload. Edit 2 : It also has a const T && overload, though I'll admit I don't understand the meaning.

    – François Andrieux
    May 2 at 19:32







  • 1





    @FrançoisAndrieux the std::get family of functions, too.

    – Brian
    May 2 at 19:34






  • 1





    See this answer.

    – lubgr
    May 2 at 19:37











  • Isn't that a forwarding reference?

    – user2357112
    May 3 at 1:52













22












22








22


3






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?









share|improve this question
















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?






c++






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 3 at 2:35









Boann

37.8k1291123




37.8k1291123










asked May 2 at 19:22









Martin B.Martin B.

862315




862315







  • 6





    std::move comes to mind. It certainly returns T&&. Edit : std::optional::value also has an T&& overload. Edit 2 : It also has a const T && overload, though I'll admit I don't understand the meaning.

    – François Andrieux
    May 2 at 19:32







  • 1





    @FrançoisAndrieux the std::get family of functions, too.

    – Brian
    May 2 at 19:34






  • 1





    See this answer.

    – lubgr
    May 2 at 19:37











  • Isn't that a forwarding reference?

    – user2357112
    May 3 at 1:52












  • 6





    std::move comes to mind. It certainly returns T&&. Edit : std::optional::value also has an T&& overload. Edit 2 : It also has a const T && overload, though I'll admit I don't understand the meaning.

    – François Andrieux
    May 2 at 19:32







  • 1





    @FrançoisAndrieux the std::get family of functions, too.

    – Brian
    May 2 at 19:34






  • 1





    See this answer.

    – lubgr
    May 2 at 19:37











  • Isn't that a forwarding reference?

    – user2357112
    May 3 at 1:52







6




6





std::move comes to mind. It certainly returns T&&. Edit : std::optional::value also has an T&& overload. Edit 2 : It also has a const T && overload, though I'll admit I don't understand the meaning.

– François Andrieux
May 2 at 19:32






std::move comes to mind. It certainly returns T&&. Edit : std::optional::value also has an T&& overload. Edit 2 : It also has a const T && overload, though I'll admit I don't understand the meaning.

– François Andrieux
May 2 at 19:32





1




1





@FrançoisAndrieux the std::get family of functions, too.

– Brian
May 2 at 19:34





@FrançoisAndrieux the std::get family of functions, too.

– Brian
May 2 at 19:34




1




1





See this answer.

– lubgr
May 2 at 19:37





See this answer.

– lubgr
May 2 at 19:37













Isn't that a forwarding reference?

– user2357112
May 3 at 1:52





Isn't that a forwarding reference?

– user2357112
May 3 at 1:52












3 Answers
3






active

oldest

votes


















17














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.






share|improve this answer























  • @FrançoisAndrieux That's covered by my 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. catch all. I know there are cases but I really didn't want to try and list them all.

    – NathanOliver
    May 2 at 19:37











  • Is there a reason to prefer returning by rvalue-ref compared to returning by value here?

    – super
    May 2 at 19:38











  • @super I take it your talking about the get_vec case? If you return by value you incur 2 move operations. Passing by rvalue reference you only have 1 move.

    – NathanOliver
    May 2 at 19:39






  • 1





    @NathanOliver Well, you can call it on any rvalue (e.g. std::move(a).get_vec()). My point is that you're potentially returning a reference to an object that's about to be destroyed. It's the same problem as returning a reference to a local function variable.

    – Cruz Jean
    May 2 at 20:03







  • 2





    std::vector<int> get_vec() && return std::move(bar); in this case ends up being better 999/1000. Can you come up with a better example?

    – Yakk - Adam Nevraumont
    May 2 at 20:08



















3















T&& t = foo(); // is this a thing? And when would t get destructed?



An rvalue reference is really similar to a lvalue reference. Think about your example like it was normal references:



T& foo();

T& t = foo(); // when is t destroyed?


The answer is that t is still valid to use as long as the object is refers to lives.



The same answer still applies to you rvalue reference example.




But... does it make sense to return an rvalue reference?



Sometimes, yes. But very rarely.



consider this:



std::vector<int> v = ...;

// type is std::tuple<std::vector<int>&&>
auto parameters = std::forward_as_tuple(std::move(v));

// fwd is a rvalue reference since std::get returns one.
// fwd is valid as long as v is.
decltype(auto) fwd = std::get<0>(parameters);

// useful for calling function in generic context without copying
consume(std::get<0>(parameters));


So yes there are example. Here, another interesting one:



struct wrapper 

auto operator*() & -> Heavy&
return heavy;


auto operator*() && -> Heavy&&
return std::move(heavy);


private:
Heavy instance;
;

// by value
void use_heavy(Heavy);

// since the wrapper is a temporary, the
// Heavy contained will be a temporary too.
use_heavy(*make_wrapper());





share|improve this answer

























  • In the last example, if the wrapper instance you use this on is a temporary, operator*() returns a reference to instance, which is likewise a temporary. So after the function returns you have a reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:51











  • @CruzJean corrected

    – Guillaume Racicot
    May 2 at 20:57


















0














I think a use case would be to explicitly give permission to "empty" some non-local variable. Perhaps something like this:



class Logger

public:
void log(const char* msg)
logs.append(msg);

std::vector<std::string>&& dumpLogs()
return std::move(logs);

private:
std::vector<std::string> logs;
;


But I admit I made this up now, I never actually used it and it also can be done like this:



std::vector<std::string> dumpLogs()
auto dumped_logs = logs;
return dumped_logs;






share|improve this answer























  • That's what the other answers have come up with as well, but in the case where this is called on a temporary object, by the time the function returns you have an (rvalue) reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:52












  • @CruzJean Well, my answer was here first and no one downvoted/complained yet so I will keep it here. I am not returning any reference to a temporary anywhere.

    – Quimby
    May 2 at 20:58











  • return std::move(logs); where the return value is a reference type and *this is a temporary (due to being an rvalue method) makes this->logs a temporary as well. That's the reference to a temporary I mean.

    – Cruz Jean
    May 2 at 22:25











  • @CruzJean Do you mean e.g. auto&& x = Logger.dumpLogs(); ? Yes, that is dangling reference, but that happens for all getters no matter what type of reference they return. My use case would be something like Logger l; /*calls to log()*/, auto logs = l.dumpLogs();/*log again.. and repeat.*/

    – Quimby
    May 3 at 10:54











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55958970%2fdoes-it-make-sense-for-a-function-to-return-an-rvalue-reference%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









17














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.






share|improve this answer























  • @FrançoisAndrieux That's covered by my 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. catch all. I know there are cases but I really didn't want to try and list them all.

    – NathanOliver
    May 2 at 19:37











  • Is there a reason to prefer returning by rvalue-ref compared to returning by value here?

    – super
    May 2 at 19:38











  • @super I take it your talking about the get_vec case? If you return by value you incur 2 move operations. Passing by rvalue reference you only have 1 move.

    – NathanOliver
    May 2 at 19:39






  • 1





    @NathanOliver Well, you can call it on any rvalue (e.g. std::move(a).get_vec()). My point is that you're potentially returning a reference to an object that's about to be destroyed. It's the same problem as returning a reference to a local function variable.

    – Cruz Jean
    May 2 at 20:03







  • 2





    std::vector<int> get_vec() && return std::move(bar); in this case ends up being better 999/1000. Can you come up with a better example?

    – Yakk - Adam Nevraumont
    May 2 at 20:08
















17














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.






share|improve this answer























  • @FrançoisAndrieux That's covered by my 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. catch all. I know there are cases but I really didn't want to try and list them all.

    – NathanOliver
    May 2 at 19:37











  • Is there a reason to prefer returning by rvalue-ref compared to returning by value here?

    – super
    May 2 at 19:38











  • @super I take it your talking about the get_vec case? If you return by value you incur 2 move operations. Passing by rvalue reference you only have 1 move.

    – NathanOliver
    May 2 at 19:39






  • 1





    @NathanOliver Well, you can call it on any rvalue (e.g. std::move(a).get_vec()). My point is that you're potentially returning a reference to an object that's about to be destroyed. It's the same problem as returning a reference to a local function variable.

    – Cruz Jean
    May 2 at 20:03







  • 2





    std::vector<int> get_vec() && return std::move(bar); in this case ends up being better 999/1000. Can you come up with a better example?

    – Yakk - Adam Nevraumont
    May 2 at 20:08














17












17








17







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.






share|improve this answer













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.







share|improve this answer












share|improve this answer



share|improve this answer










answered May 2 at 19:34









NathanOliverNathanOliver

101k17145227




101k17145227












  • @FrançoisAndrieux That's covered by my 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. catch all. I know there are cases but I really didn't want to try and list them all.

    – NathanOliver
    May 2 at 19:37











  • Is there a reason to prefer returning by rvalue-ref compared to returning by value here?

    – super
    May 2 at 19:38











  • @super I take it your talking about the get_vec case? If you return by value you incur 2 move operations. Passing by rvalue reference you only have 1 move.

    – NathanOliver
    May 2 at 19:39






  • 1





    @NathanOliver Well, you can call it on any rvalue (e.g. std::move(a).get_vec()). My point is that you're potentially returning a reference to an object that's about to be destroyed. It's the same problem as returning a reference to a local function variable.

    – Cruz Jean
    May 2 at 20:03







  • 2





    std::vector<int> get_vec() && return std::move(bar); in this case ends up being better 999/1000. Can you come up with a better example?

    – Yakk - Adam Nevraumont
    May 2 at 20:08


















  • @FrançoisAndrieux That's covered by my 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. catch all. I know there are cases but I really didn't want to try and list them all.

    – NathanOliver
    May 2 at 19:37











  • Is there a reason to prefer returning by rvalue-ref compared to returning by value here?

    – super
    May 2 at 19:38











  • @super I take it your talking about the get_vec case? If you return by value you incur 2 move operations. Passing by rvalue reference you only have 1 move.

    – NathanOliver
    May 2 at 19:39






  • 1





    @NathanOliver Well, you can call it on any rvalue (e.g. std::move(a).get_vec()). My point is that you're potentially returning a reference to an object that's about to be destroyed. It's the same problem as returning a reference to a local function variable.

    – Cruz Jean
    May 2 at 20:03







  • 2





    std::vector<int> get_vec() && return std::move(bar); in this case ends up being better 999/1000. Can you come up with a better example?

    – Yakk - Adam Nevraumont
    May 2 at 20:08

















@FrançoisAndrieux That's covered by my 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. catch all. I know there are cases but I really didn't want to try and list them all.

– NathanOliver
May 2 at 19:37





@FrançoisAndrieux That's covered by my 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. catch all. I know there are cases but I really didn't want to try and list them all.

– NathanOliver
May 2 at 19:37













Is there a reason to prefer returning by rvalue-ref compared to returning by value here?

– super
May 2 at 19:38





Is there a reason to prefer returning by rvalue-ref compared to returning by value here?

– super
May 2 at 19:38













@super I take it your talking about the get_vec case? If you return by value you incur 2 move operations. Passing by rvalue reference you only have 1 move.

– NathanOliver
May 2 at 19:39





@super I take it your talking about the get_vec case? If you return by value you incur 2 move operations. Passing by rvalue reference you only have 1 move.

– NathanOliver
May 2 at 19:39




1




1





@NathanOliver Well, you can call it on any rvalue (e.g. std::move(a).get_vec()). My point is that you're potentially returning a reference to an object that's about to be destroyed. It's the same problem as returning a reference to a local function variable.

– Cruz Jean
May 2 at 20:03






@NathanOliver Well, you can call it on any rvalue (e.g. std::move(a).get_vec()). My point is that you're potentially returning a reference to an object that's about to be destroyed. It's the same problem as returning a reference to a local function variable.

– Cruz Jean
May 2 at 20:03





2




2





std::vector<int> get_vec() && return std::move(bar); in this case ends up being better 999/1000. Can you come up with a better example?

– Yakk - Adam Nevraumont
May 2 at 20:08






std::vector<int> get_vec() && return std::move(bar); in this case ends up being better 999/1000. Can you come up with a better example?

– Yakk - Adam Nevraumont
May 2 at 20:08














3















T&& t = foo(); // is this a thing? And when would t get destructed?



An rvalue reference is really similar to a lvalue reference. Think about your example like it was normal references:



T& foo();

T& t = foo(); // when is t destroyed?


The answer is that t is still valid to use as long as the object is refers to lives.



The same answer still applies to you rvalue reference example.




But... does it make sense to return an rvalue reference?



Sometimes, yes. But very rarely.



consider this:



std::vector<int> v = ...;

// type is std::tuple<std::vector<int>&&>
auto parameters = std::forward_as_tuple(std::move(v));

// fwd is a rvalue reference since std::get returns one.
// fwd is valid as long as v is.
decltype(auto) fwd = std::get<0>(parameters);

// useful for calling function in generic context without copying
consume(std::get<0>(parameters));


So yes there are example. Here, another interesting one:



struct wrapper 

auto operator*() & -> Heavy&
return heavy;


auto operator*() && -> Heavy&&
return std::move(heavy);


private:
Heavy instance;
;

// by value
void use_heavy(Heavy);

// since the wrapper is a temporary, the
// Heavy contained will be a temporary too.
use_heavy(*make_wrapper());





share|improve this answer

























  • In the last example, if the wrapper instance you use this on is a temporary, operator*() returns a reference to instance, which is likewise a temporary. So after the function returns you have a reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:51











  • @CruzJean corrected

    – Guillaume Racicot
    May 2 at 20:57















3















T&& t = foo(); // is this a thing? And when would t get destructed?



An rvalue reference is really similar to a lvalue reference. Think about your example like it was normal references:



T& foo();

T& t = foo(); // when is t destroyed?


The answer is that t is still valid to use as long as the object is refers to lives.



The same answer still applies to you rvalue reference example.




But... does it make sense to return an rvalue reference?



Sometimes, yes. But very rarely.



consider this:



std::vector<int> v = ...;

// type is std::tuple<std::vector<int>&&>
auto parameters = std::forward_as_tuple(std::move(v));

// fwd is a rvalue reference since std::get returns one.
// fwd is valid as long as v is.
decltype(auto) fwd = std::get<0>(parameters);

// useful for calling function in generic context without copying
consume(std::get<0>(parameters));


So yes there are example. Here, another interesting one:



struct wrapper 

auto operator*() & -> Heavy&
return heavy;


auto operator*() && -> Heavy&&
return std::move(heavy);


private:
Heavy instance;
;

// by value
void use_heavy(Heavy);

// since the wrapper is a temporary, the
// Heavy contained will be a temporary too.
use_heavy(*make_wrapper());





share|improve this answer

























  • In the last example, if the wrapper instance you use this on is a temporary, operator*() returns a reference to instance, which is likewise a temporary. So after the function returns you have a reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:51











  • @CruzJean corrected

    – Guillaume Racicot
    May 2 at 20:57













3












3








3








T&& t = foo(); // is this a thing? And when would t get destructed?



An rvalue reference is really similar to a lvalue reference. Think about your example like it was normal references:



T& foo();

T& t = foo(); // when is t destroyed?


The answer is that t is still valid to use as long as the object is refers to lives.



The same answer still applies to you rvalue reference example.




But... does it make sense to return an rvalue reference?



Sometimes, yes. But very rarely.



consider this:



std::vector<int> v = ...;

// type is std::tuple<std::vector<int>&&>
auto parameters = std::forward_as_tuple(std::move(v));

// fwd is a rvalue reference since std::get returns one.
// fwd is valid as long as v is.
decltype(auto) fwd = std::get<0>(parameters);

// useful for calling function in generic context without copying
consume(std::get<0>(parameters));


So yes there are example. Here, another interesting one:



struct wrapper 

auto operator*() & -> Heavy&
return heavy;


auto operator*() && -> Heavy&&
return std::move(heavy);


private:
Heavy instance;
;

// by value
void use_heavy(Heavy);

// since the wrapper is a temporary, the
// Heavy contained will be a temporary too.
use_heavy(*make_wrapper());





share|improve this answer
















T&& t = foo(); // is this a thing? And when would t get destructed?



An rvalue reference is really similar to a lvalue reference. Think about your example like it was normal references:



T& foo();

T& t = foo(); // when is t destroyed?


The answer is that t is still valid to use as long as the object is refers to lives.



The same answer still applies to you rvalue reference example.




But... does it make sense to return an rvalue reference?



Sometimes, yes. But very rarely.



consider this:



std::vector<int> v = ...;

// type is std::tuple<std::vector<int>&&>
auto parameters = std::forward_as_tuple(std::move(v));

// fwd is a rvalue reference since std::get returns one.
// fwd is valid as long as v is.
decltype(auto) fwd = std::get<0>(parameters);

// useful for calling function in generic context without copying
consume(std::get<0>(parameters));


So yes there are example. Here, another interesting one:



struct wrapper 

auto operator*() & -> Heavy&
return heavy;


auto operator*() && -> Heavy&&
return std::move(heavy);


private:
Heavy instance;
;

// by value
void use_heavy(Heavy);

// since the wrapper is a temporary, the
// Heavy contained will be a temporary too.
use_heavy(*make_wrapper());






share|improve this answer














share|improve this answer



share|improve this answer








edited May 2 at 20:57

























answered May 2 at 19:35









Guillaume RacicotGuillaume Racicot

17.1k53875




17.1k53875












  • In the last example, if the wrapper instance you use this on is a temporary, operator*() returns a reference to instance, which is likewise a temporary. So after the function returns you have a reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:51











  • @CruzJean corrected

    – Guillaume Racicot
    May 2 at 20:57

















  • In the last example, if the wrapper instance you use this on is a temporary, operator*() returns a reference to instance, which is likewise a temporary. So after the function returns you have a reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:51











  • @CruzJean corrected

    – Guillaume Racicot
    May 2 at 20:57
















In the last example, if the wrapper instance you use this on is a temporary, operator*() returns a reference to instance, which is likewise a temporary. So after the function returns you have a reference to an object whose lifetime has ended (undefined behavior).

– Cruz Jean
May 2 at 20:51





In the last example, if the wrapper instance you use this on is a temporary, operator*() returns a reference to instance, which is likewise a temporary. So after the function returns you have a reference to an object whose lifetime has ended (undefined behavior).

– Cruz Jean
May 2 at 20:51













@CruzJean corrected

– Guillaume Racicot
May 2 at 20:57





@CruzJean corrected

– Guillaume Racicot
May 2 at 20:57











0














I think a use case would be to explicitly give permission to "empty" some non-local variable. Perhaps something like this:



class Logger

public:
void log(const char* msg)
logs.append(msg);

std::vector<std::string>&& dumpLogs()
return std::move(logs);

private:
std::vector<std::string> logs;
;


But I admit I made this up now, I never actually used it and it also can be done like this:



std::vector<std::string> dumpLogs()
auto dumped_logs = logs;
return dumped_logs;






share|improve this answer























  • That's what the other answers have come up with as well, but in the case where this is called on a temporary object, by the time the function returns you have an (rvalue) reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:52












  • @CruzJean Well, my answer was here first and no one downvoted/complained yet so I will keep it here. I am not returning any reference to a temporary anywhere.

    – Quimby
    May 2 at 20:58











  • return std::move(logs); where the return value is a reference type and *this is a temporary (due to being an rvalue method) makes this->logs a temporary as well. That's the reference to a temporary I mean.

    – Cruz Jean
    May 2 at 22:25











  • @CruzJean Do you mean e.g. auto&& x = Logger.dumpLogs(); ? Yes, that is dangling reference, but that happens for all getters no matter what type of reference they return. My use case would be something like Logger l; /*calls to log()*/, auto logs = l.dumpLogs();/*log again.. and repeat.*/

    – Quimby
    May 3 at 10:54















0














I think a use case would be to explicitly give permission to "empty" some non-local variable. Perhaps something like this:



class Logger

public:
void log(const char* msg)
logs.append(msg);

std::vector<std::string>&& dumpLogs()
return std::move(logs);

private:
std::vector<std::string> logs;
;


But I admit I made this up now, I never actually used it and it also can be done like this:



std::vector<std::string> dumpLogs()
auto dumped_logs = logs;
return dumped_logs;






share|improve this answer























  • That's what the other answers have come up with as well, but in the case where this is called on a temporary object, by the time the function returns you have an (rvalue) reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:52












  • @CruzJean Well, my answer was here first and no one downvoted/complained yet so I will keep it here. I am not returning any reference to a temporary anywhere.

    – Quimby
    May 2 at 20:58











  • return std::move(logs); where the return value is a reference type and *this is a temporary (due to being an rvalue method) makes this->logs a temporary as well. That's the reference to a temporary I mean.

    – Cruz Jean
    May 2 at 22:25











  • @CruzJean Do you mean e.g. auto&& x = Logger.dumpLogs(); ? Yes, that is dangling reference, but that happens for all getters no matter what type of reference they return. My use case would be something like Logger l; /*calls to log()*/, auto logs = l.dumpLogs();/*log again.. and repeat.*/

    – Quimby
    May 3 at 10:54













0












0








0







I think a use case would be to explicitly give permission to "empty" some non-local variable. Perhaps something like this:



class Logger

public:
void log(const char* msg)
logs.append(msg);

std::vector<std::string>&& dumpLogs()
return std::move(logs);

private:
std::vector<std::string> logs;
;


But I admit I made this up now, I never actually used it and it also can be done like this:



std::vector<std::string> dumpLogs()
auto dumped_logs = logs;
return dumped_logs;






share|improve this answer













I think a use case would be to explicitly give permission to "empty" some non-local variable. Perhaps something like this:



class Logger

public:
void log(const char* msg)
logs.append(msg);

std::vector<std::string>&& dumpLogs()
return std::move(logs);

private:
std::vector<std::string> logs;
;


But I admit I made this up now, I never actually used it and it also can be done like this:



std::vector<std::string> dumpLogs()
auto dumped_logs = logs;
return dumped_logs;







share|improve this answer












share|improve this answer



share|improve this answer










answered May 2 at 19:32









QuimbyQuimby

1,548814




1,548814












  • That's what the other answers have come up with as well, but in the case where this is called on a temporary object, by the time the function returns you have an (rvalue) reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:52












  • @CruzJean Well, my answer was here first and no one downvoted/complained yet so I will keep it here. I am not returning any reference to a temporary anywhere.

    – Quimby
    May 2 at 20:58











  • return std::move(logs); where the return value is a reference type and *this is a temporary (due to being an rvalue method) makes this->logs a temporary as well. That's the reference to a temporary I mean.

    – Cruz Jean
    May 2 at 22:25











  • @CruzJean Do you mean e.g. auto&& x = Logger.dumpLogs(); ? Yes, that is dangling reference, but that happens for all getters no matter what type of reference they return. My use case would be something like Logger l; /*calls to log()*/, auto logs = l.dumpLogs();/*log again.. and repeat.*/

    – Quimby
    May 3 at 10:54

















  • That's what the other answers have come up with as well, but in the case where this is called on a temporary object, by the time the function returns you have an (rvalue) reference to an object whose lifetime has ended (undefined behavior).

    – Cruz Jean
    May 2 at 20:52












  • @CruzJean Well, my answer was here first and no one downvoted/complained yet so I will keep it here. I am not returning any reference to a temporary anywhere.

    – Quimby
    May 2 at 20:58











  • return std::move(logs); where the return value is a reference type and *this is a temporary (due to being an rvalue method) makes this->logs a temporary as well. That's the reference to a temporary I mean.

    – Cruz Jean
    May 2 at 22:25











  • @CruzJean Do you mean e.g. auto&& x = Logger.dumpLogs(); ? Yes, that is dangling reference, but that happens for all getters no matter what type of reference they return. My use case would be something like Logger l; /*calls to log()*/, auto logs = l.dumpLogs();/*log again.. and repeat.*/

    – Quimby
    May 3 at 10:54
















That's what the other answers have come up with as well, but in the case where this is called on a temporary object, by the time the function returns you have an (rvalue) reference to an object whose lifetime has ended (undefined behavior).

– Cruz Jean
May 2 at 20:52






That's what the other answers have come up with as well, but in the case where this is called on a temporary object, by the time the function returns you have an (rvalue) reference to an object whose lifetime has ended (undefined behavior).

– Cruz Jean
May 2 at 20:52














@CruzJean Well, my answer was here first and no one downvoted/complained yet so I will keep it here. I am not returning any reference to a temporary anywhere.

– Quimby
May 2 at 20:58





@CruzJean Well, my answer was here first and no one downvoted/complained yet so I will keep it here. I am not returning any reference to a temporary anywhere.

– Quimby
May 2 at 20:58













return std::move(logs); where the return value is a reference type and *this is a temporary (due to being an rvalue method) makes this->logs a temporary as well. That's the reference to a temporary I mean.

– Cruz Jean
May 2 at 22:25





return std::move(logs); where the return value is a reference type and *this is a temporary (due to being an rvalue method) makes this->logs a temporary as well. That's the reference to a temporary I mean.

– Cruz Jean
May 2 at 22:25













@CruzJean Do you mean e.g. auto&& x = Logger.dumpLogs(); ? Yes, that is dangling reference, but that happens for all getters no matter what type of reference they return. My use case would be something like Logger l; /*calls to log()*/, auto logs = l.dumpLogs();/*log again.. and repeat.*/

– Quimby
May 3 at 10:54





@CruzJean Do you mean e.g. auto&& x = Logger.dumpLogs(); ? Yes, that is dangling reference, but that happens for all getters no matter what type of reference they return. My use case would be something like Logger l; /*calls to log()*/, auto logs = l.dumpLogs();/*log again.. and repeat.*/

– Quimby
May 3 at 10:54

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55958970%2fdoes-it-make-sense-for-a-function-to-return-an-rvalue-reference%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020