簡體   English   中英

C ++首先會發生什么-破壞函數的參數或處理函數的返回值?

[英]C++ what happens first - destruction of function's parameters or handling of function's return values?

我有以下代碼:

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 之前發生? 請注意,如果我在foo主體中聲明一個本地thing ,那么它會在分配發生之前被破壞,正如我所期望的那樣。

帶有此簽名:

int foo(thing x) {
    return 5;
}

您正在創建一個函數,其中thing的實例為參數。 參數由方法的調用者傳遞,這表示此處的表達式:

newThing = foo(bar);

創建從bar復制的thing的臨時對象。 這些臨時對象的生存期到完整表達式的結尾,因此在分配發生后將調用此臨時對象的析構函數。

為什么會這樣? 因為編譯器僅生成一個稱為foo函數,並且該函數無法在本地構造x它不知道使用哪個參數構造它。 可能有多個可能有效的構造函數和幾個不同的參數集。 因此,編譯器必須在調用的調用者方構造臨時對象。

參數由調用者而不是方法構造和銷毀。 “ foo()的本地事物”根本不是foo()的,而是調用者的:調用者將其銷毀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM