考虑下面的代码析构函数不叫:当异常被抛出
#include <iostream>
using namespace std;
class Test {
static int count;
int id;
public:
Test() {
count++;
id = count;
cout << "Constructing object number " << id << endl;
if(id == 4)
throw 4;
}
~Test() { cout << "Destructing object number " << id << endl; }
};
int Test::count = 0;
int main() {
try {
Test array[5];
} catch(int i) {
cout << "Caught " << i << endl;
}
}
上面的代码产生以下输出:
Constructing object number 1
Constructing object number 2
Constructing object number 3
Constructing object number 4
Destructing object number 3
Destructing object number 2
Destructing object number 1
Caught 4
我想析构函数总是被调用时,对象变得超出范围即使发生异常时也是如此。为什么在这种情况下不调用其中的Test
实例的析构函数?
我已经编辑你的问题到更适合堆栈溢出的东西。请按照[问题指南](http://stackoverflow.com/questions/how-to-ask)以备将来参考,否则您的问题可能会被降低/关闭。 – 2012-01-28 06:19:15