ostream chaining, output order

前端 未结 5 1251
礼貌的吻别
礼貌的吻别 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:12

    Hexadecimal Output

    Before C++11, the class std::ostream has a conversion function to void*. Since your print function returns std::ostream&, when evaluating std::cout << print(...), the returned std::ostream lvalue will be implicitly converted to void* and then be outputted as a pointer value. This is why there is a hexadecimal output.

    Since C++11, this conversion function is replaced by an explicit conversion function to bool, so trying to output an std::ostream object becomes ill-formed.

    Evaluation Order

    Before C++17, overloaded operator is considered a function call for analyzing evaluation order, and evaluation order of different arguments of a function call is unspecified. So it is not strange that the print function is evaluated firstly, which causes How are you? is outputted firstly.

    Since C++17, the evaluation order of operands of operator << is strictly from left to right, and operands of overloaded operator share the same evaluation order as those of the bulit-in one (see more details here). So your program will always get the output (assume print returns something able to be outputted)

    Hello, world! How are you?
    something returned by print
    

    LIVE EXAMPLE

提交回复
热议问题