抛出导致析构函数被调用的异常会导致程序崩溃

0 c++ exception-handling exception

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

似乎不是被捕获的异常,程序就被终止了.不过,如果我删除的构造,除了被逮住.

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

Bri*_*ian 14

一个界外球的表达,没有操作,因为在你的代码:

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

我假设f()被调用,而异常被处理(我想你是直接从调用它main或东西).因此,std::terminate被称为.

该对象a无关紧要.