I had the following code in a sample application:
ostream& operator<< (ostream& os, const ReferenceTest& rt)
{
os << rt.counter; //In this scenario, rt has a public int called counter
}
I was surprised to learn that this code compiled without issue using GCC 4.6.1. It fails when using Visual Studio 2010 for the reason I would have expected, namely that I’m not returning a reference to an ostream. However, the output for the program when compiled for the two platforms is identical (I have a trivial main() that writes test output).
Which is standards compliant? Am I missing something obvious here?
-Derek
Did you compile with warnings enabled? I get
warning: control reaches end of non-void functionwith g++.You certainly don’t want a compiler to stop at the first error in your code. You want it to catch as many as it can in one swell foop. To do this, the compiler has to patch your buggy code so it can press on. In this case, the patch is obvious: Return the stream provided as an argument.
Never trust those “fixes” supplied for free by the compiler. They are anything but free. Fix your code instead.
And always compile with warnings enabled.