Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ - wrong destructor gets called

Tags:

c++

destructor

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?

like image 533
Van Coding Avatar asked Mar 24 '23 05:03

Van Coding


1 Answers

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

like image 64
Sergey Kalinichenko Avatar answered Apr 19 '23 23:04

Sergey Kalinichenko