-3

According to the post r-value causes a warning without the use of std::move, I'm wondering if the following code has undefined behavior:

struct Animal
{
  virtual void foo() const
  {
    std::cout << "error" << std::endl;
  }
};

struct Dog : public Animal
{
  void foo() const
  {
    std::cout << "wuff" << std::endl;
  }
};

struct A
{
  A( const Animal& a) : _a( a ) {}

  void foo()
  {
    _a.foo();
  }


  const Animal& _a;
};

int main()
{
  A a( Dog{} );
  a.foo();

}

On my machine, the output is (as expected) wuff.

Community
  • 1
  • 1
abraham_hilbert
  • 2,221
  • 1
  • 13
  • 30

1 Answers1

4

Indeed, a.a_ is a dangling reference in the statement a.foo();, and so the evaluation of the expression _a.foo has undefined behaviour. The lifetime of the temporary object Dog{} ends at the end of the full-expression (and is not extended).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084