繁体   English   中英

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

[英]Throwing an exception which causes a destructor to be called crashes the program

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

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.

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

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

没有操作数的throw-expression ,如您的代码所示:

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

我假设在处理异常时调用f() (我想您是直接从main或其他对象调用它)。 因此,将调用std::terminate

对象a不相关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM