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