0

I have an code example like below:

std::vector<std::string> func() {
  std::vector result;
  // insert value into the result.
  return result;
}

void other_func() {
const auto& var = func();
....
}

It could compile. What will the var hold? Is it a temporary value of the func()?

Alicia
  • 1
  • 1
  • Note that while `const` references like the one you wrote can extend the lifetime of temporaries, it isn't true in all contexts. It is generally safe when the reference is just one local variable. – François Andrieux Oct 06 '20 at 17:29
  • @FrançoisAndrieux The lifetime of a temporary bound to a reference is extended always when the lifetime of the reference is longer than the temporary. However, that extension of lifetime is not transferred to other references, which is typical mistaken assumption. – eerorika Oct 06 '20 at 17:44
  • Thanks for your explanation! – Alicia Oct 07 '20 at 18:22

0 Answers0