我有以下代码:
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();
}
当我运行它时,在我的程序到达 的地方getchar()
,我希望看到以下输出:
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
相反,我得到了这个:
create
create
copy
assign
destroy
请注意,分配和销毁已与我的预期交换。
这是怎么回事?为什么分配似乎发生在本地x
被破坏之前?请注意,如果我thing
在 foo 的主体中声明一个 local,它会在分配发生之前被破坏,正如我所期望的那样。