2

次のコードがあります。

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 が、私が予想していたものと入れ替わっていることに注意してください。

これどうしたの?ローカルが破棄される前に割り当てが行われるように見えるのはなぜですか? xfoo の本体でローカルを宣言すると、thing予想どおり、割り当てが行われる前に破棄されることに注意してください。

4

2 に答える 2

1

パラメーターは、メソッドではなく、呼び出し元によって構築および破棄されます。「foo() のローカルなもの」は foo() のものではなく、呼び出し元のものです。呼び出し元が破棄します。

于 2013-10-22T19:44:20.080 に答える