zap*_*oyd 8 c++ istream libstdc++ libc++
当与libstdc ++和libc ++链接时,以下(玩具)程序返回不同的东西.这是libc ++中的错误还是我不明白istream eof()是如何工作的?我尝试在linux和mac os x上使用g ++并在mac os x上运行它,使用和不使用-std = c ++ 0x.我的印象是,在尝试读取(通过get()或其他东西)实际上失败之前,eof()不会返回true.这就是libstdc ++的行为方式,而不是libc ++的行为方式.
#include <iostream>
#include <sstream>
int main() {
std::stringstream s;
s << "a";
std::cout << "EOF? " << (s.eof() ? "T" : "F") << std::endl;
std::cout << "get: " << s.get() << std::endl;
std::cout << "EOF? " << (s.eof() ? "T" : "F") << std::endl;
return 0;
}
Thor:~$ g++ test.cpp
Thor:~$ ./a.out
EOF? F
get: 97
EOF? F
Thor:~$ clang++ -std=c++0x -stdlib=libstdc++ test.cpp
Thor:~$ ./a.out
EOF? F
get: 97
EOF? F
Thor:~$ clang++ -std=c++0x -stdlib=libc++ test.cpp
Thor:~$ ./a.out
EOF? F
get: 97
EOF? T
Thor:~$ clang++ -stdlib=libc++ test.cpp
Thor:~$ ./a.out
EOF? F
get: 97
EOF? T
Run Code Online (Sandbox Code Playgroud)
编辑:这是由于旧版本的libc ++解释C++标准的方式.LWG问题2036讨论了这种解释,它被认为是不正确的,并且libc ++被改变了.
当前的libc ++在测试中给出了与libstdc ++相同的结果.
老答案:
你的理解是正确的.
istream::get() 执行以下操作:
good(),并设置failbit是否返回false(这会将一个failbit添加到其他位设置的流中),(§27.7.2.1.2[istream::sentry]/2)good()为false,则返回eof并且不执行任何其他操作.rdbuf()->sbumpc()或rdbuf()->sgetc()(§27.7.2.1[istream]/2)sbumpc()或sgetc()返回eof,则设置eofbit.(§27.7.2.1[istream]/3)和failbit(§27.7.2.2.3[istream.unformatted]/4)§27.7.2.2.3[istream.unformatted]/1)并在允许的情况下重新抛出.(引自C++ 11的章节,但C++ 03具有所有相同的规则,根据§27.6.*)
现在让我们来看看实现:
libc ++(当前的svn版本)定义了get()的相关部分
sentry __s(*this, true);
if (__s)
{
__r = this->rdbuf()->sbumpc();
if (traits_type::eq_int_type(__r, traits_type::eof()))
this->setstate(ios_base::failbit | ios_base::eofbit);
else
__gc_ = 1;
}
Run Code Online (Sandbox Code Playgroud)
libstdc ++(与gcc 4.6.2一起提供)定义了与之相同的部分
sentry __cerb(*this, true);
if (__cerb)
{
__try
{
__c = this->rdbuf()->sbumpc();
// 27.6.1.1 paragraph 3
if (!traits_type::eq_int_type(__c, __eof))
_M_gcount = 1;
else
__err |= ios_base::eofbit;
}
[...]
if (!_M_gcount)
__err |= ios_base::failbit;
Run Code Online (Sandbox Code Playgroud)
如您所见,sbumpc()当且仅当sbumpc()返回eof时,两个库都会调用并设置eofbit.
您的测试用例使用两个库的最新版本为我生成相同的输出.
| 归档时间: |
|
| 查看次数: |
1195 次 |
| 最近记录: |