C++: constructor and destructor do not go in pairs due to class reference returned by a function
<p>As we all know, constructor and destructor go in pairs.</p>

<p>But the following piece of code doesn't behave that way,
the contructor is called twice but the destructor is called only once!</p>

<pre><code>{
    Animal ahe;
    ahe = CreateAnimal();
}
</code></pre>

<p>Please read on for more detailed explanation.</p>

<p>Suppose there is a class named Animal, and we have the following code:</p>

<pre><code>int main(int argc, char* argv[])
{
    Animal ahe;

    return 0;
}
</code></pre>

<p>It is expected that Animal's contructor and destructor will both be called once and only once.
And when I run the code, it behaves exactly as what I have expected.</p>

<p>But it looks quite weird when it comes to the following code, when a reference of Animal is returned by a function.
When I run the code, the contructor is called twice but the destructor is called only once!</p>

<pre><code>#include "stdafx.h"
#include "stdio.h"
#include "iostream.h"

class Animal
{
public:
    Animal();
    Animal(long age);

    ~Animal();
private:
    long m_age;
};

Animal::~Animal()
{
    cout&lt;&lt;"Animal::~Animal()"&lt;&lt;"age="&lt;&lt;m_age&lt;&lt;endl;
}
Animal::Animal()
{
    m_age = 1;
    cout&lt;&lt;"Animal::Animal()"&lt;&lt;"age="&lt;&lt;m_age&lt;&lt;endl;
}

Animal::Animal(long age)
{
    m_age = age;
    cout&lt;&lt;"Animal::Animal()"&lt;&lt;"age="&lt;&lt;m_age&lt;&lt;endl;
}

Animal&amp; CreateAnimal()
{
    Animal *pAnimal = new Animal(5);

    return *pAnimal;
}

int main(int argc, char* argv[])
{
    Animal ahe;

    ahe = CreateAnimal();

    return 0;
}
</code></pre>

<p>//output</p>

<pre><code>Animal::Animal()age=1
Animal::Animal()age=5
Animal::~Animal()age=5
</code></pre>

<p>Obviously, destructor of the first object is not called, why?
The problem can be serious, if Animal has a lot of resource which needs to be released in its destructor.</p>
