C++首先发生什么 - 破坏函数的参数或处理函数的返回值?

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

本文关键字:参数 函数 处理函数 返回值 什么 C++      更新时间:2023-10-16

我有以下代码:

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()'s local thing' 根本不是 foo() 的,它是调用者的:调用者破坏了它。