gpt4 book ai didi

c++ - 调用 std::terminate 是否违反 noexcept?

转载 作者:行者123 更新时间:2023-12-05 09:30:29 25 4
gpt4 key购买 nike

假设我有一个可以调用 std::terminate 的函数:

int my_fun(int i) noexcept {
if(i==0) std::terminate();
return 3/i;
}

我可以声明这个noexcept吗?据我所知,没有任何东西被“抛出”......

最佳答案

指定noexcept 的效果是您声明该方法不抛出。换句话说,它是一个非抛出函数。尽管如此,当抛出异常时,将调用 std::terminate。来自 cppreference :

Non-throwing functions are permitted to call potentially-throwing functions. Whenever an exception is thrown and the search for a handler encounters the outermost block of a non-throwing function, the function std::terminate or std::unexpected (until C++17) is called:

因此,您甚至可以在 my_fun 中抛出异常,它也会调用 std::terminatenoexcept 只是意味着异常不会从 my_fun 向上传递调用堆栈。

关于c++ - 调用 std::terminate 是否违反 noexcept?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69553581/

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