1 Reply Latest reply: Nov 23, 2011 10:02 AM by Steve.Clamage-Oracle RSS

    Suprising results when upgrading to 12.2

    Willoch
      h2. What do you think the following program will do?
      #include <iostream>
      #include <fstream>
      using namespace std;

      int main() {
      if(ofstream("/dev/stdout") << "Hello World!" <<endl)
      cout <<"Success" <<endl;
      }
      h3. Surprise ?
      CC main.cc && ./a.out
      113fc
      Success
      CC main.cc -library=stlport4 && ./a.out
      0x00011f74
      Success
      CC main.cc -features=rvalueref && ./a.out
      Hello World!
      Success
      /local1/SS121/sunstudio12.1/bin/CC main.cc && ./a.out
      Hello World!
      Success

      gcc gives same result as 12.2, so I do not doubt that it is correct. Just very surprising.

      Maybe we should get a warning when the rvalue reference rule causes another method/function to be called?

      The reason for this behavior is that operator<<(const void *) is a member of ostream, while
      operator<<(ostream&, const char *) is not

      So because a temporary can not be a non-const reference, the compiler picks operator<<(const void *) .
        • 1. Re: Suprising results when upgrading to 12.2
          Steve.Clamage-Oracle
          Historically, C++ compilers varied in whether they allowed a reference-to-non-const to be bound to an rvalue such as a temporary object.
          T foo();
          const T& q = foo(); // always OK
          T& r = foo(); // ???
          Since many compilers (notably g++) allowed it in the past, Studio C++ also allowed it for compatibility.

          With modern template uses, particularly in BOOST code, allowing code such as the marked line changed the results of function overloading and the selection of template specializations.

          To allow valid code to work, we changed the default behavior of the compiler (refer to the compiler documentation) to disallow the technically invalid code. We also added an option to restore the old behavior to allow existing code to work. If you have a mix of old and new code, you need to modify the old code to make it valid.

          I think we could issue a warning when actually binding a reference-to-non-const to an rvalue. Please file an RFE (request for enhancement) via your support channel if you have a support contract. If not, you can file an RFE at http://bugs.sun.com.