0

Found on this blog

http://davekilian.com/cpp-type-erasure.html

class Cow;

template <typename T>
class AnimalWrapper : public MyAnimal
{
    const T &m_animal;

public:
    AnimalWrapper(const T &animal)
        : m_animal(animal)
    { }
};

MyAnimal* animal = new AnimalWrapper(Cow());

Is this valid C++? I believe it will compile, but on seeing this immediatly thought undefined behaviour.

I thought that references were implemented like pointers, however I am now questioning this.

In my mind, it would be like doing this:

int *p = nullptr;
{
    int temp;
    p = &temp;
}
cout << *p << endl; // undefined behaviour, stack allocated temporary object "temp" is no longer on the stack

As far as I can see, there are two possibilities.

  • I am wrong, and references do not exactly behave like pointers
  • The code in this blog produces undefined behaviour

Can anyone enlighten me? If this is valid C++, then why?

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

0 Answers0