简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM