I have the following code:
class thing {
public:
thing(const thing& x) { cout << "copy" << endl; }
thing() { cout << "create" << endl; }
~thing() { cout << "destroy" << endl; }
thing& operator=(const int& rhs) { cout << "assign" << endl; }
};
int foo(thing x) {
return 5;
}
int main() {
thing bar;
thing newThing;
newThing = foo(bar);
getchar();
}
When I run this, at the point where my program reaches the getchar()
, I expect to see the following output:
create // since bar is default constructed
create // since newThing is default constructed
copy // since bar gets passed by value into foo
destroy // since foo's local thing `x` is destructed when foo ends
assign // since the 5 returned by foo is assigned to newThing
Instead, I get this:
create
create
copy
assign
destroy
Note that assign and destroy have swapped from what I expected.
What's up with this? Why does the assignment appear to happen before the local x
is destructed? Note that if I declare a local thing
in the body of foo, it gets destructed before the assignment happens, as I would expect.