C ++ - invalid destructor called

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?

+4
source share
2 answers

a = X (2); => the statement of assignment of an expression call, and the a.id data element is initialized using the temporary object method .id ie 2.

a = X (2); => expression invokes the default assignment operator provided by the compiler and executing a yellow copy.

The X (2) expression creates a temporary object, and the timeobject.id file is initialized 2.

The first time you deconstruct a get call when a temporary object receives another call to the object.

+2
source

In your case, only one object is destroyed, namely the temporary X(2) on the right side of your destination. The original X(1) not destroyed because it is assigned by assignment. When the time comes for its destruction, it will also print destroying 2 .

However, modified X(2) (starting as X(1) ) is supported by an infinite loop, so it will not be destroyed either. Removing an infinite loop eliminates this ( demo ).

+5
source

Source: https://habr.com/ru/post/1491089/


All Articles