以下代码适用于gcc 4.4.
但是gcc 4.7会让断言失败.
#include <assert.h>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string input("abcdefg");
stringstream iss(input);
ostringstream oss;
oss << iss.rdbuf();
assert (!iss.eof());
(void) iss.peek();
assert (iss.eof());
// the following assertion will fail with gcc 4.7
assert( streamoff(iss.tellg()) ==
streamoff(input.length()) );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在gcc 4.7中,如果istream已达到EOF,则tellg()将返回-1.不会调用pubseekoff()和seekoff()在gcc 4.4中它不是问题.
应该是哪种行为,gcc 4.4还是gcc 4.7?为什么?
根据C++ 11第27.7.2.3p40节,
如果
fail() != false,返回pos_type(-1)
因此,gcc 4.7具有当前版本的C++的正确行为(假设peek()在流的末尾导致failbit设置,并且它在哨兵构造期间,因为skipws默认设置).
看一下C++ 03的措辞,它是一样的.27.6.1.3p37.因此,您在gcc 4.4中描述的行为是一个错误.