请考虑以下代码:
上面的代码将产生以下输出:
#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 实例的析构函数呢?