c++visual-c++g++stream-operators

Is there an compiler bug in vc++? (I am a beginner)


There are different effect between vc++(debug mode) and g++, with this code

test.hh

class Test
{
public:
    int a, b, c;
    Test(int a, int b, int c) : a{ a }, b{ b }, c{ c } {      }

    Test& operator++();
    Test  operator++(int);

};
std::ostream& operator<<(std::ostream& os, const Test& t);

test.cc

std::ostream& operator<<(std::ostream& os, const Test& t)
{
    os << "{ " << t.a << ',' << t.b << ',' << t.c << " }";
    return os;
}

Test Test::operator++(int)
{
    Test temp{ *this };
    operator++();
    return temp;
}

Test& Test::operator++()
{
    ++a; ++b; ++c;
    return *this;
}

main.cc

Test t{ 1,2,3 };

std::cout << t << '\n'
          << t++ << '\n'
          << t;

in vc++ the result of execution is

{ 2,3,4 }
{ 1,2,3 }
{ 2,3,4 }

but in g++ it is

{ 1,2,3 }
{ 1,2,3 }
{ 2,3,4 }

so, Is there an compiler bug in vc++ or something what I has not learned.


Solution

  • Unfortunately << has a psychological effect of pushing the idea of "sequencing".

    While std::cout << a() << b() << c() conveys the idea of computing a(), then b() and then c() this is (was) false. You only know they will be put in the output stream in sequence, but they can be computed in any order (before C++17).

    This has been fixed recently (so may be the difference you are observing depends on which C++ standard you are using), but unfortunately only for common special cases like the left-shift operator that is overloaded for stream output (IMO another sad choice of C++ for a few reasons).