libstdc和libc:operator >>在bitset上的行为差异

请考虑以下代码:

#include <bitset>
#include <sstream>
#include <iostream>

int main(int argc, char* argv[])
{
    std::stringstream stream;
    std::bitset<1> bitset(1);
    std::cout<<"before = "<<bitset[0]<<std::endl;
    stream<<"4";
    stream>>bitset;
    std::cout<<"after = "<<bitset[0]<<std::endl;
    return 0;
}

使用libstdc在g下编译,结果是:

> g++ bitset_empty.cpp -o bitset_empty
> ./bitset_empty 
before = 1
after = 1

使用libc在clang下编译,结果是:

> clang++ -stdlib=libc++ bitset_empty.cpp -o bitset_empty
> ./bitset_empty 
before = 1
after = 0

哪一个是对的?两者(因为未定义的行为?)? GCC?铛?

最佳答案
根据我的理解,libc就在这里,但它并不是唯一正确的行为.

N4140 §20.6.4 [bitset.operators]

Effects: Extracts up to N characters from is. Stores these characters in a temporary object str of type basic_string<charT,
traits>
, then evaluates the expression x = bitset<N>(str).
Characters are extracted and stored until any of the following occurs:

  • N characters have been extracted and stored;
  • end-of-file occurs on the input sequence;
  • the next input character is neither is.widen(’0’) nor is.widen(’1’) (in which case the input character is not extracted).

If no characters are stored in str, calls
is.setstate(ios_base::failbit) (which may throw ios_base::failure
(27.5.5.4))

重要的是要注意x = bitset< N>(str)不是有条件的.如果没有抛出ios_base :: failure,那么这就是执行的表达式.并且bitset< N>(“s”)(即,空字符串)是0.

因此,根据我的理解,您的bitset应该归零或者应该抛出上述异常.

如果没有抛出异常,您可能想要测试您的操作是否成功(通过测试返回的流).

转载注明原文:libstdc和libc:operator >>在bitset上的行为差异 - 代码日志