This is due to the fact that you are not destroying A(1), you are being assigned to it A(2), add your example by adding an assign operator :
class A
{
int a;
public:
A(int a) : a(a) { cout << "Constructor a=" << a << endl; }
~A() { cout << "Destructor a=" << a << endl; }
void print() { cout << "Print a=" << a << endl; }
A &operator=(const A &other) {
cout << "Assign operator old=" << a << " a=" << other.a << endl;
a = other.a;
}
};
This will lead to:
[vyktor@grepfruit tmp]$ ./a.out
Constructor a=1
Print a=1
Constructor a=2
Assign operator old=1 a=2 <- This line explains why destructor is not called
Destructor a=2
Print a=2
Destructor a=2
If you have one of these:
- Destructor - destroy all members of an object
- .
- .
. .