【问题标题】:Setting the Terminate and Unexpected Handler设置终止和意外处理程序
【发布时间】:2017-11-04 20:06:55
【问题描述】:

你能解释一下吗:

terminate_handler set_terminate(terminate_handler f) throw();

还有这个:

unexpected_handler set_unexpected (unexpected_handler f) throw();

要更改我们使用的终止处理程序,必须使用set_terminate(),如上所示,但我无法理解/解释上述表格。谁能解释一下。

我也很难理解这一点:

terminate_handler set_terminate(terminate_handler f) throw();

这里, f 是指向新终止处理程序的指针。函数 返回一个指向旧终止处理程序的指针。新的终止 handler 必须是 terminate_handler 类型,其定义如下:

typedef void(*terminate_handler)();

【问题讨论】:

    标签: c++ exception-handling


    【解决方案1】:

    terminate_handler 是函数指针的类型定义。设置终止处理程序时,您将指针传递给要在终止时调用的函数。这就是set_terminate 的论点。该函数返回旧指针。这样,如果您只想在短时间内使用自己的终止处理程序,您可以在完成后恢复之前的处理程序:

    void my_terminator() {
        // whatever
    }
    
    int main() {
        // terminate here calls default handler
    
        terminate_handler old_handler = set_terminate(my_terminator);
        // now, terminate will call `my_terminator`
    
        set_terminate(old_handler);
        // now, terminate will call the default handler
    
        return 0;
    }
    

    【讨论】:

    • 很好解释,谢谢!我有一个困惑 q1:为什么有 'throw()' 关键字,它是动态异常规范吗?
    • throw(),因为空括号,表示该函数不会抛出任何异常。这些天它会写成noexcept
    • @Pete Becker 最后一个问题也是terminate_handler set_terminate (terminate_handler f) throw(); set_terminate 函数的原型
    • @rimiro — 是的,它是一个函数原型。就像int my_function(int i) throw();。只需将int 替换为terminate_handler。同样,terminate_handler 是函数指针的 typedef 名称。也就是说,它是一个类型的名称,很像int
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2013-04-08
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多