C++:什么时候在最后一条语句之前调用析构函数?
C++: When is a destructor called before the last statement?
所以我有一些 C++ 代码:
#include <iostream>
using namespace std;
class C {
public:
C() {i = 9; cout << "C0:" << i << endl;}
C(int i0) {i = i0; cout << "C1:" << i << endl;}
~C() {cout << "C2:" << i << endl;}
private:
int i;
};
void f(int i) {
C c(i);
}
int main(int argc, char* argv[]) {
for (int i = 0; i < 1; i++) {
cout << "X" << endl;
f(i);
cout << "Y" << endl;
}
}
输出为:
X
C1:0
C2:0
Y
这很奇怪,因为 C2:0 行是析构函数的一部分,据我所知,它是在最后一条语句之后调用的。所以我的问题是在什么样的情况下在最后一条语句之前调用析构函数?
自动变量(f()
中的 c
)在它们所在的堆栈消失时被清理。
所以在这种情况下,您的 f(i)
电话正在返回。对于对象,这包括调用析构函数。
当程序正确退出时,全局变量和静态变量也会在程序退出时被清除。如果它通过未捕获的异常退出,它们可能不会被清理(这不是必需的)。
对象 C
在函数 f 中创建。因此,C
在 f
函数作用域结束时被销毁,在 main 中调用 f(i)
之后,f
作用域被销毁,并且 C
对象的析构函数被调用。
This is strange because the line C2:0 is part of the destructor which I've learned is called after the last statement.
在包含作为 class.
实例的变量的作用域的最后一条语句 之后调用析构函数
C
在 f(int i)
函数的范围内创建和销毁,因此 C 的析构函数打印 "C2:0"。 f 完成,然后才打印 Y。
所以我有一些 C++ 代码:
#include <iostream>
using namespace std;
class C {
public:
C() {i = 9; cout << "C0:" << i << endl;}
C(int i0) {i = i0; cout << "C1:" << i << endl;}
~C() {cout << "C2:" << i << endl;}
private:
int i;
};
void f(int i) {
C c(i);
}
int main(int argc, char* argv[]) {
for (int i = 0; i < 1; i++) {
cout << "X" << endl;
f(i);
cout << "Y" << endl;
}
}
输出为:
X
C1:0
C2:0
Y
这很奇怪,因为 C2:0 行是析构函数的一部分,据我所知,它是在最后一条语句之后调用的。所以我的问题是在什么样的情况下在最后一条语句之前调用析构函数?
自动变量(f()
中的 c
)在它们所在的堆栈消失时被清理。
所以在这种情况下,您的 f(i)
电话正在返回。对于对象,这包括调用析构函数。
当程序正确退出时,全局变量和静态变量也会在程序退出时被清除。如果它通过未捕获的异常退出,它们可能不会被清理(这不是必需的)。
对象 C
在函数 f 中创建。因此,C
在 f
函数作用域结束时被销毁,在 main 中调用 f(i)
之后,f
作用域被销毁,并且 C
对象的析构函数被调用。
This is strange because the line C2:0 is part of the destructor which I've learned is called after the last statement.
在包含作为 class.
实例的变量的作用域的最后一条语句 之后调用析构函数C
在 f(int i)
函数的范围内创建和销毁,因此 C 的析构函数打印 "C2:0"。 f 完成,然后才打印 Y。