5
std::string f(){
   return "xx";
}

int main(){

const std::string& ref = f();
// use ref
}

f returns temporary string by value. main "catch" it by const reference. Is it ok in C++?

user10121051
  • 137
  • 5

2 Answers2

1

It is fine. Temporary could be bound to lvalue-reference to const or rvalue reference, and its lifetime will be extended to the lifetime of the reference.

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference

songyuanyao
  • 163,662
  • 15
  • 289
  • 382
1

Yes it's fine: the lifetime of the std::string is extended to the lifetime of the const reference.

But note that the behaviour is not transitive: i.e. don't assign a const reference to ref, expecting that to extend the lifetime even further.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
  • 2
    That's a new idea to me, some code illustrating it would be helpful – john Sep 19 '18 at 07:15
  • 1
    `string const& PassThru(string const& s) { return s; }` called with `string const& oops = PassThru("kaboom");`, the temporary with "kaboom" will not be lifetime extended. – Eljay Sep 19 '18 at 13:26