As we all know, constructor and destructor go in pairs.
But the following piece of code doesn't behave that way, the contructor is called twice but the destructor is called only once!
{
Animal ahe;
ahe = CreateAnimal();
}
Please read on for more detailed explanation.
Suppose there is a class named Animal, and we have the following code:
int main(int argc, char* argv[])
{
Animal ahe;
return 0;
}
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.
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!
#include "stdafx.h"
#include "stdio.h"
#include "iostream.h"
class Animal
{
public:
Animal();
Animal(long age);
~Animal();
private:
long m_age;
};
Animal::~Animal()
{
cout<<"Animal::~Animal()"<<"age="<<m_age<<endl;
}
Animal::Animal()
{
m_age = 1;
cout<<"Animal::Animal()"<<"age="<<m_age<<endl;
}
Animal::Animal(long age)
{
m_age = age;
cout<<"Animal::Animal()"<<"age="<<m_age<<endl;
}
Animal& CreateAnimal()
{
Animal *pAnimal = new Animal(5);
return *pAnimal;
}
int main(int argc, char* argv[])
{
Animal ahe;
ahe = CreateAnimal();
return 0;
}
//output
Animal::Animal()age=1
Animal::Animal()age=5
Animal::~Animal()age=5
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.