是否可以输入两次terminate_handler?

发布于 2024-09-15 08:05:04 字数 98 浏览 10 评论 0原文

我在终止处理程序中进行了一些清理,并且可能会引发异常。我是否需要担心捕获它以防止递归调用终止处理程序?对于 gcc,这似乎不可能发生,我们只是进入中止状态。标准是这样还是行为未定义?

I have some clean up in a terminate_handler and it is possible to throw an exception. Do I need to worry about catching it to prevent recursive calls to the terminate_handler? With gcc, it seems this can't happen and we just go into abort. Is that true of the standard or is the behavior undefined?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浊酒尽余欢 2024-09-22 08:05:04

终止处理程序不允许返回(§18.6.3.1/2);它必须结束程序(默认处理程序调用abort())。如果它包括:

void my_terminate()
{
    throw 5;
}

您将得到未定义的行为,因为您将在没有终止程序的情况下离开该函数(因为异常传播)。因此,如果您有可能抛出的代码,请确保捕获所有异常,如下所示:

void my_terminate()
{
    try
    {
        // stuff
    }
    catch(...)
    {
        // too bad
    }

    abort();
}

但是(回答标题问题),我没有看到任何限制它再次输入的内容,所以这在技术上应该没问题:

void my_terminate()
{
    static int counter = 0;

    if (counter++ < 5)
        terminate();

    abort();
}

A terminate handler is not allowed to return (§18.6.​3.1/2); it must end the program (the default handler calls abort()). If it consisted of:

void my_terminate()
{
    throw 5;
}

You'd get undefined behavior, because you would leave the function (because the exception propagates) without having terminated the program. So if you have code that could throw, make sure you catch all exceptions, like this:

void my_terminate()
{
    try
    {
        // stuff
    }
    catch(...)
    {
        // too bad
    }

    abort();
}

However (to answer the title question), I don't see anything that restricts it from being entered again, so this should be technically be fine:

void my_terminate()
{
    static int counter = 0;

    if (counter++ < 5)
        terminate();

    abort();
}
温馨耳语 2024-09-22 08:05:04

不,您无法从 std::terminate 恢复正常的程序流程。但是,您可以意外函数中抛出不同的异常。 Terminate 就是这样做的——程序执行在完成后终止。

编辑:

也就是说,你不应该在 std::terminate 中做任何复杂的事情 - 如果你在 terminate 中,那么事情已经足够严重了,你不应该这样做尝试继续 - 并且出于同样的原因,您不应该尝试在 std::terminate 中分配内存之类的事情 - 如果程序由于内存不足而在那里怎么办健康)状况?你对此无能为力。

No, you cannot resume normal program flow from std::terminate. You can, however, throw a different exception from the unexpected function. Terminate does just that -- program execution terminates after it completes.

EDIT:

That said, you shouldn't be doing anything complicated in std::terminate -- if you're in terminate then things have blown up sufficiently that you should not be trying to continue -- and you shouldn't try to do things like allocate memory in std::terminate for the same reason -- what if the program is in there as a result of a low memory condition? There's nothing you can do about it there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文