我对 throw() 说明符的理解是,任何未在说明符中列出的异常类型在从给定函数内抛出时都会导致调用 std::unexpected()。
所以我希望以下代码的输出是“意外调用”,但我看到的却是“捕获到异常”。我正在用 VS2013 编译它,它没有实现 noexcept
,这就是我使用 throw()
的原因。
#include <iostream>
#include <exception>
void testFunc() throw () {
throw std::exception();
}
int main(void) {
std::set_unexpected([](){
std::cout << "unexpected called";
});
try {
testFunc();
}
catch (...) {
std::cerr << "Caught an exception";
}
return 0;
}
为什么不调用 std::unexpected?
最佳答案
https://msdn.microsoft.com/en-us/library/vstudio/wfa0edys%28v=vs.120%29.aspx说:
Visual C++ departs from the ISO C++ Standard in its implementation of exception specifications.
[...]
[...] if an exception is thrown out of a function marked
throw()
, the Visual C++ compiler will not callunexpected
[...].[...]
Due to code optimizations that might be performed by the C++ compiler (based on the assumption that the function does not throw any C++ exceptions) if a function does throw an exception, the program may not execute correctly.
此外,为支持上述内容,https://msdn.microsoft.com/en-us/library/vstudio/awbt5tew.aspx说:
The C++ Standard requires that
unexpected
is called when a function throws an exception that is not on its throw list. The current implementation does not support this.
关于c++ - 当我在用空 throw() 说明符指定的函数中抛出异常时,为什么不调用 std::unexpected()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29064666/