引发导致调用析构函数的异常会使程序崩溃



考虑这一小段代码,它实际上是更大代码库的一部分:

class A
{
public:
A()
{
std::cout << "A" << std::endl;
}
~A()
{
std::cout << "~A" << std::endl;
}
};
void f()
{
A a;
throw;
}
void g()
{
try
{
f();
}
catch(...)
{
std::cout << "Caught" << std::endl;
}
}

对于我的特定情况,输出结果是

A
~A
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

似乎不是捕获异常,而是程序刚刚终止。但是,如果我删除 A 的构造函数,异常确实会被捕获。

如果不仔细分析代码,是否有可能知道是什么导致了这种行为?

一个没有操作数的抛出表达式,就像在你的代码中一样:

  • 重新引发当前处理的异常(同一对象,而不是它的副本)
  • 或者,如果当前没有处理异常,则调用std::terminate

我假设在处理异常时没有调用f()(我想您直接从main或其他东西调用它)。因此,std::terminate被称为。

对象a无关紧要。