gpt4 book ai didi

c++ - 抛出导致调用析构函数的异常会使程序崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 14:37:49 24 4
gpt4 key购买 nike

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

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 的构造函数,异常被捕获。

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

最佳答案

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

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

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

对象 a 是无关紧要的。

关于c++ - 抛出导致调用析构函数的异常会使程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com