Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lifetime extension for function taking parameter by const& and returning by const&

In C++ when you have the following:

std::string get_string();
std::string const& v = get_string();

The lifetime of the temporary returned from get_string() is extended for the same lifetime of the reference v;

If I have the following:

std::string const& get_string(std::string const& p) {
  return p;
}

std::string const& v = 
get_string(std::string{"Hello"});

Is the lifetime of the temporary extended? or is this a dangling reference;

My understanding is that the temporary is bound to the lifetime of p and that only exists for the duration of the function and that secondary references to the temporary dont extend the lifetime.

What is the expected result?

like image 474
Blair Davidson Avatar asked Nov 07 '22 17:11

Blair Davidson


1 Answers

Yes, the lifetime of the temporary is not extended further more; after the full expression the reference v becomes dangled.

std::string const& v = get_string(std::string{"Hello"});
// v becomes dangled now

My understanding is that the temporary is bound to the lifetime of p and that only exists for the duration of the function

To be precisely, the temporary exists until the end of the full expression, not only the duration of the function.

  • a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.

In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference to which the temporary was bound, does not affect its lifetime.

That means something like auto sz = get_string(std::string{"Hello"}).size(); is fine.

like image 167
songyuanyao Avatar answered Nov 15 '22 05:11

songyuanyao