Get string by const reference

Viewed 407
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++?

2 Answers

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

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.

Related