Why is the destructor 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; } 

Conclusion:

 60 70 60 70 10 20 

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

+5
source share
3 answers

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

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

+11
source

Since the operator+ you specified returns a temporary object, which is subsequently assigned to a2 . Both temporary and a2 will be destroyed (temporary at the end of the instruction, a2 at the end of main ) by printing their values.

+7
source

Replace

 a2=a1+50; 

with just

 a1+50; 

and you will see why.

+2
source

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


All Articles