This question already has answers here:
Are destructors called after a throw in C++?

(3 个回答)


7年前关闭。




我有一个这样的代码:
class myclass
{
     myclass()
     {
        // doing some init here
      }
     ~myclass()
     {
        // doing some important clean up here
     }
     void Do()
     {
          //    doing some work which may throw exception
      }
}

我以这种方式使用这个类:
MyFunction()
{
    myclass mc;
    mc.do();
 }

我的问题是:

如果 do 函数出现异常,会发生什么? myclass 的析构函数被调用了吗?

如果不是,处理此类情况的最佳方法是什么?假设我没有源代码并且我确定析构函数中发生了什么。

最佳答案



如果您有任何处理程序,它将被处理。



当然是。标准引用了这个::



整个过程称为“堆栈展开”:

关于c++ - 异常后清理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20397165/

10-11 22:07
查看更多