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:
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();
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