The difference in the behavior of betwen libstdc ++ and libc ++: operator >> on bits

Consider the following code:

#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;
}

Compiled under g++c libstdc++, the result is:

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

Compiled in clang++s libc++, result:

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

Which one is right? Both (due to undefined behavior?)? Gcc? Clang?

+4
source share
2 answers

From my point of view, lib ++ is here, but this is not the only correct behavior.

N4140 §20.6.4 [bitset.operators]

: N . str basic_string<charT, traits>, x = bitset<N>(str). , :

  • N ;
  • ;
  • is.widen(’0’), is.widen(’1’) ( ).

str, is.setstate(ios_base::failbit) ( ios_base::failure(27.5.5.4))

, x = bitset<N>(str) . ios_base::failure , . bitset<N>(""s) (.. ) 0.

, , bitset .

, , ( ).

+2

,

stream>>bitset;

. , 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";
    if ( stream>>bitset )
    {
       std::cout<<"after = "<<bitset[0]<<std::endl;
    }
    else
    {
       std::cout << "Failed to restore bitset from stream.\n";
    }
    return 0;
}

g++ 4.9.3:

before = 1
Failed to restore bitset from stream.
+2

Source: https://habr.com/ru/post/1661677/


All Articles