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()'s local thing' 根本不是 foo() 的,它是调用者的:调用者破坏了它。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类