Van Coding
Van Coding

Reputation: 24534

c++ - wrong destructor gets called

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?

Upvotes: 4

Views: 230

Answers (2)

Ajay yadav
Ajay yadav

Reputation: 4511

a = X(2); => expression call assignment operator and a.id data member is initialized by temporaryobject.id i.e 2.

a = X(2); => expression calls the default assignment operator that is provided by compiler and do the sallow copy.

X(2) expression create the temporary object and temporaryobject.id is initialized with 2.

First time deconstruct get call when temporary object get called another for a object.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

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).

Upvotes: 5

Related Questions