通过 const 获取参数并通过 const 返回的函数的生命周期延长

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

在 C++ 中,当您具有以下条件时:

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

从 get_string() 返回的临时对象的生命周期延长为与引用 v 相同的生命周期;

如果我有以下情况:

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

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

临时的生命周期延长了吗?或者这是一个悬而未决的参考;

我的理解是临时绑定到p的生命周期 并且它只在函数的持续时间内存在,并且对临时对象的二次引用不会延长生命周期。

预期结果是什么?

是的,临时的生命周期没有进一步延长;在完整表达式之后,引用 v 变为悬空。

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

准确地说,temporary 一直存在到完整表达式的末尾,而不仅仅是函数的持续时间。

  • 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.

这意味着像 auto sz = get_string(std::string{"Hello"}).size(); 这样的东西是可以的。