1

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
  • 11
  • 2
  • 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
  • Well, this const is a local, so, it's not extending the lifetime of the return value? Aren't return values usually popped off the stack into a register? And if a local variable is set to that value, then it would be pushed back onto the stack; but the compiler might see that and just leave it on the stack to begin with, and turn references to that variable into references to the stack location, as is common for locals anyway, right? So the only difference I would expect const to make, here, is to make it so the code in this function is prevented by the compiler from changing the value. – Shavais Jun 20 '23 at 22:30

0 Answers0