析构函数没有被调用时抛出一个异常 [英] Destructor not called when an exception is thrown

查看:329
本文介绍了析构函数没有被调用时抛出一个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code:

#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;
  }
}

在code以上产生下面的输出:

The code above produces the following output:

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

我想析构函数总是被调用时,对象变成超出范围,即使抛出异常。为什么不是测试实例析构函数调用这种情况下呢?

I thought destructors were always called when objects become out of scope, even when exceptions are thrown. Why isn't one of the Test instances' destructors called in this case?

推荐答案

您正在创建 5 测试数组对象,但在创建后,你抛出一个异常 3 完整对象,将引发异常,而在构造函数中的 4 个对象。在 4 个对象的结构是不完整的,直到构造函数的右括号为止。

You are creating an array of 5 Test objects but you throw an exception after you create 3 complete objects, The exception is thrown while in the constructor of the 4th object. The construction of the 4th object is not complete until the closing brace of the constructor is reached.

该协议栈开卷调用析构函数的 3 以相反的顺序完全构造的对象中,他们创建,因为 4 和第 5 个对象从来没有构建的析构函数他们永远不会被调用。

The stack unwinds calling destructor for those 3 completely constructed objects in the opposite order in which they were created, since the 4th and 5th object were never constructed the destructor for them is never called.

有例外的规则是:
一旦有异常抛出析构函数为范围内的所有完全创建的对象将被调用。
一个完全创建的对象是一个其构造函数被调用干净,没有任何例外。

The rule for exception is:
Once an exception is thrown destructors for all completely created objects within that scope will be called.
An completely created object is one whose constructor has been called cleanly without any exceptions.

这篇关于析构函数没有被调用时抛出一个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆