destructor for returned object called twice??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

// Visual C++ Express 2008

#include <iostream>

using namespace std;

class myClass
{
public:
	myClass() : myInt(staticInt+=100) {
		printf("default ctor myInt(%d)\n", myInt);
	}
	myClass(myClass & mc) {
		myInt = mc.myInt+1;
		printf("copy ctor(%d)\n", myInt);
	}
	~myClass() {
		printf("myClass dtor myInt(%d) \n", myInt);
	}
	static int staticInt;
	int myInt;
};

myClass operator+(myClass mc1, myClass mc2) {
	printf("declaring temp\n");
	myClass temp;
	printf("done with declaring temp\n");
	temp.myInt += mc1.myInt + mc2.myInt;
	printf("about to return temp, myInt(%d) \n", temp.myInt);
	return temp;
}

int myClass::staticInt = 0;

int mainFunc() {
	char *myCharPtr;
	myClass mc1, mc2, mc3;

	mc3 = mc1 + mc2; //same as mc3 = operator+(mc1, mc2);
	printf("done with operator+ return from mainFunc()\n");
	return 0;
}

int main() {
	mainFunc();
	return 0;
}


Output:


default ctor myInt(100)
default ctor myInt(200)
default ctor myInt(300)
copy ctor(201)
copy ctor(101)
declaring temp
default ctor myInt(400)
done with declaring temp
about to return temp, myInt(702)
copy ctor(703)
myClass dtor myInt(702)
myClass dtor myInt(101)
myClass dtor myInt(201)
myClass dtor myInt(703)
done with operator+ return from mainFunc()
myClass dtor myInt(703)
myClass dtor myInt(200)
myClass dtor myInt(100)
Press any key to continue . . .


I am trying to get a better understanding of all the constructors, destructors that get called "behind the scenes". I am deliberately passing by value. I don't understand why the destructor for myClass object with myInt=703 gets called the a second time?

I understand that to return "temp 702" a copy 703 is made of it using copy ctor, then temp itself 702 is destructed as we leave operator+ (along with the 2 arguments passed by value 101 and 201) then we set mc3 = mc1 + mc2 using the temporary 703 then we destruct the temporary 703 then we are "done with operator+ return from mainFunc()", and then suddenly why are we calling 703 destructor again??


The first time it is called [with value 703] is to destroy the object created on line 27. The second time is to destroy mc3 (created on line 38).

Argh... kicking myself, it's so obvious now that you say it, I got mixed up since mc3 and temp have the same value (as they should) and mc3 no longer = 300. That was silly of me.

Thanks jsmith much appreciated
Topic archived. No new replies allowed.