我是否应该期望在 CentOS6 和 CentOS7 之间处理 fstream 异常时有不同的行为

Should I expect different behavior with fstream exception handling between CentOS6 and CentOS7?

本文关键字:异常 fstream 处理 之间 是否 期望 CentOS7 CentOS6      更新时间:2023-10-16

我正在使用异常处理从带有 fstream 对象的文件中读取数据。由于逻辑的实现方式,代码将在命中文件末尾时抛出 fstream::failure 异常后在 fstream 上执行 tellg()。此执行流程不一定是有意为之,但在 Windows (MSVS 2010) 或 CentOS6 上运行时不会造成任何问题。但是,在 CentOS7 上运行时,我得到了一个核心转储。如果我在 tellg() 之前添加一个调用来清除 fstream,一切都很好。

抛出的错误是:

在抛出"std::ios_base::失败"实例后终止调用 what(): basic_ios::清除

有人可以提供关于这种行为变化是否在意料之中的见解吗?

gcc 和 libstdc++ 的适用版本是:

对于 CentOS6:

    GCC 版本 4.4.7
  • 20120313 (Red Hat 4.4.7-11) (GCC)
  • /
  • usr/lib64/libstdc++.so.6.0.13

对于 CentOS7:

    GCC 版本 4.8.2
  • 20140120 (Red Hat 4.8.2-16) (GCC)
  • /
  • usr/lib64/libstdc++.so.6.0.19

下面提供了执行此问题的代码示例:

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
   fstream in;
   in.exceptions(ifstream::failbit);
   cout << "Before open" << endl;
   in.open("in.txt", ios::in);
   cout << "After open" << endl;
   try
   {
      string s;
      while ( 1 )
      {
         getline(in, s);
         cout << s << endl;
      }
   }
   catch(fstream::failure e)
   {
      cout << "EOF Exception." << endl;
   }
   catch(...)
   {
      cout << "Unhandled Exception." << endl;
   }
   // --- uncomment this to make it work ---  in.clear();
   in.tellg();
   return 0;
}

感谢您的帮助!

如 PR 26211 所示,GCC 4.6.0 实现了 DR 419 的解析,因此新行为是有意为之。

标准中存在缺陷,该

缺陷已修复,因此更改了GCC的库以匹配标准中的新规范。