gpt4 book ai didi

c++ - 我应该期望 CentOS6 和 CentOS7 之间 fstream 异常处理的不同行为吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:19:15 26 4
gpt4 key购买 nike

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

抛出的错误是:

terminate called after throwing an instance of 'std::ios_base::failure' what(): basic_ios::clear

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

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

对于 CentOS6:

  • gcc 版本 4.4.7 20120313(红帽 4.4.7-11)(GCC)
  • /usr/lib64/libstdc++.so.6.0.13

对于 CentOS7:

  • gcc 版本 4.8.2 20140120(红帽 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 的库已更改以匹配标准中的新规范。

关于c++ - 我应该期望 CentOS6 和 CentOS7 之间 fstream 异常处理的不同行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28973591/

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