0

I have a class Foo that store a const reference to a Bar. If I pass a temporary Bar to the constructor, I thought that storing that would be bad, but it works correctly. Does storing the rvalue somehow extend the lifetime of the temporary?

#include <iostream>

struct Bar {
  int a;
};

struct Foo {
  Foo(const Bar& bar) : bar{bar} {}
  
  const Bar& bar;
};

int main() {
  Bar bar{5};
  Foo foo{bar};
  Foo foo2{Bar{10}};

  std::cout << foo.bar.a << std::endl; // Prints 5, OK
  std::cout << foo2.bar.a << std::endl; // Prints 10, why?
}
Jojolatino
  • 696
  • 5
  • 11

0 Answers0