Reputation: 3
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
Upvotes: 0
Views: 140
Reputation: 33126
Did you compile with warnings enabled? I get warning: control reaches end of non-void function
with 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.
Upvotes: 2
Reputation: 81379
Missing something other than the return statement? The lack of it is undefined behavior (I would even expect it to be a compile time error for such simple case). It may happen that the returned value from os << rt.counter
expression happens to be placed at the same location where the return value for the whole operator<<
is expected, making it work just by chance.
Upvotes: 1