I have an understanding problem with destructors.
In the following example:
#include <iostream>
using namespace std;
class X{
public:
int id;
X(int id){
this->id = id;
}
~X(){
cout << "destroying " << id;
}
};
int main(){
X a(1);
a = X(2);
while(true);
return 0;
}
I get the following output: destroying 2
This is totally unexpected to me, because I thought that the destructor gets always called, when an object stops to exist.
But in this example, it's object 1 that stops to exist and gets replaced by object 2. But instead of calling the destructor of object 1, the destructor of object 2 gets called.
Can someone explain this?
In your case, only one object gets destroyed - namely, the temporary X(2)
on the right-hand side of your assignment. The original X(1)
does not get destroyed, because it gets overwritten by the assignment. When the time comes for it to get destroyed, it will print destroying 2
as well.
However, the modified X(2)
(that started off as X(1)
) is kept alive by the infinite loop, so it does not get destroyed either. Removing the infinite loop fixes this (demo).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With