我有一个代码片段,我用 nullptr 作为参数调用 rethrow_exception 。 文档说参数应该是非空的,但我想知道,如果我传递 nullptr,行为是未定义还是已知?
我每次都会遇到 bad_exception。然而,这个link表示行为未定义。
std::string msg;
try
{
std::rethrow_exception(nullptr);
}
catch (std::bad_exception &ex)
{
msg = ex.what();
}
catch (std::exception &ex)
{
msg = ex.what();
}
catch (...)
{
msg = "uncaught exception!";
}
有谁可以评论到底发生了什么吗?
最佳答案
这是未定义的行为。
标准says :
[[noreturn]] void rethrow_exception(exception_ptr p);
Preconditions:
p
is not a null pointer.Throws: The exception object to which
p
refers.
违反前提条件是 UB ( [res.on.required]/2
)。您可能观察到的任何行为均符合标准; C++ 标准对可能发生的情况没有任何限制。所以不要这样做。
关于c++ - std::rethrow_exception(nullptr) 未定义行为或 bad_exception?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59285088/