Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning by value to rvalue reference

I'm studying rvalue references and I have a doubt in the following code:

string func() {
    return "Paul";
}

int main()
{
    string&& nodanger = func();
    // The lifetime of the temporary is extended
    // to the life-time of the reference.
    return 0;
}

The question is: what does func() return?

I believe this is what happens:

  • func returns a prvalue "Paul" (is this a const char * due to a rvalue->pointer conversion?)
  • a string object is implicitly constructed (which ctor is used?)
  • due to reference collapsing rules it is bound to "nodanger" (does this behave any differently from a string& normal reference?)
like image 486
Albert Avatar asked Dec 08 '25 09:12

Albert


1 Answers

Your func() function returns an std::string prvalue. The constructor being used to construct the std::string is

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

This prvalue is bound to the rvalue reference nodanger, which extends its lifetime to match that of the reference itself. Reference collapsing doesn't come into play here.

does this behave any differently from a string& normal reference?

The code wouldn't compile if nodanger was a string& because you can't bind rvalues to non-const lvalue references. The lifetime extension behavior in your example is identical to the following case

std::string const& nodanger = func();
like image 179
Praetorian Avatar answered Dec 10 '25 00:12

Praetorian