简体   繁体   中英

Why destructor is called twice?

I have the following code:

#include <cstdio>
#include <iostream>
using namespace std;

class A
{
    int a, b;
public:
    A() : A(5, 7) {}
    A(int i, int j)
    {
        a = i;
        b = j;
    }
    A operator+(int x)
    {
        A temp;
        temp.a = a + x;
        temp.b = b + x;
        return temp;
    }
    ~A() { cout << a << " " << b << endl; }
};

int main()
{
    A a1(10, 20), a2;
    a2 = a1 + 50;
}

Output it shows:

60 70
60 70
10 20

The code works almost as expected. The problem is it prints the values of object a2 twice... that means the destructor is called twice... but why it is called twice?

During the assignment a2=a1+50 , a temporary object containing a1+50 is allocated.

This object is destroyed immediately after it is copied into a2 .

Because the operator+ you defined returns a temporary object that is subsequently assigned to a2 . Both the temporary and a2 get destroyed (the temporary at the end of the statement, a2 at the end of main ), printing their values.

Replace

a2=a1+50;

with just

a1+50;

and you will see why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM