ostream chaining, output order

前端 未结 5 1299
礼貌的吻别
礼貌的吻别 2020-11-30 11:38

I have a function that takes an ostream reference as an argument, writes some data to the stream, and then returns a reference to that same stream, like so:

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 12:06

    The reason is that your print() function will be evaluated before the rest of the statement and return a reference to cout which is then actually printed as a pointer (cout << cout). This order of evaluation is actually unspecified behavior, but seems to be the case with your compiler.

    As for defining a stream aware "function" that actually has defined behavior with the same functionality, this would work;

    #include 
    
    template 
      std::basic_ostream& print ( std::basic_ostream& os )
    {
            os << " How are you?" << std::endl;
            return os;
    }
    
    int main() {
      std::cout << "Hello, world!" << print << std::endl;
    }
    

    See also this answer for a little more detail on what "unspecified" actually means in this case.

提交回复
热议问题