背景
我有这段简单的代码:
#include <iostream>
#include <fstream>
#include <system_error>
int main(int argc, char *argv[]) {
std::ifstream file;
file.exceptions(std::ios::failbit | std::ios::badbit);
try {
file.open("a_file_does_not_exist.txt", std::ios::in);
file.close();
} catch(const std::ios_base::failure& err) {
std::cerr << err.code() << std::endl;
return -1;
}
return 0;
}
为了完整,这是编译命令:
g++ -std=c++11 -g // ...
编译器版本为g++ (GCC) 6.1.1。
平台:arch-linux 4.7.2-1。
问题
正如你所想象的那样,文件不存在,因此方法file.open(...)
将引发异常。问题在于当我运行代码时,未处理异常,并且调用了std::terminate
。
奇怪的是输出:
terminate called after throwing an instance of 'std::ios_base::failure'
what(): basic_ios::clear
Annullato (core dump creato)
正如您所读的,抛出异常的类是“std::ios_base::failure”,但我的捕获语句确实正确。我的问题是:我漏掉了什么?
NSt8ios_base7failureB5cxx11E
。也许在代码库中有两个定义,一个是C++03的,一个是C++11的,而03版本在open
中隐藏了11版本? - jaggedSpireios_base::failure
在 C++11 中经历了 ABI 更改。libstdc++ 在尝试管理这个转换过程中出现了一些混乱。https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145 - T.C.