I have a 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 conclusion: destruction 2
This is completely unexpected for me, because I thought that the destructor is always called when the object ceases to exist.
But in this example, object 1 ceases to exist and is replaced by object 2. But instead of calling the destructor of object 1, the destructor of object 2 is called.
Can someone explain this?
source share