简体   繁体   中英

Overloaded operator<< returning ostream&

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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM