次のコードがあります。
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
assign と destroy が、私が予想していたものと入れ替わっていることに注意してください。
これどうしたの?ローカルが破棄される前に割り当てが行われるように見えるのはなぜですか? x
foo の本体でローカルを宣言すると、thing
予想どおり、割り当てが行われる前に破棄されることに注意してください。