#op<<()

23 messages · Page 1 of 1 (latest)

polar owl
#

is there any difference between std::cout << 1 << 2; and std::cout << 1; std::cout << 2; as far as how it's interpreted or code generated? The question is more about how op<<() works, not cout. can be any class with op<<(), just using cout as example.

meager sageBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

pale veldt
#

the typical operator<< for a "stream" takes as lhs argument a stream, and returns a reference to that stream

#

so in terms of "intended" effect there shouldn't be any observable difference between chaining multiple << vs splitting them across two explicit invocations on the same object

#

but this is just convention/typical implementation, if you start doing funky things, there's nothing that prevents you from returning a completely different object/type/stream after the first <<, at which point you'd have to go and look at whatever the implementation is doing

lime schooner
fossil sentinel
#

The only potential difference is if you do std::cout << some_funky_type

lime schooner
#

Whatever the difference between mov rdi, rax and mov edi, OFFSET FLAT:_ZSt4cout are.

fossil sentinel
#

Since it could eg have an overload special cased for particular types of ostream, or it might return a different object then you passed in

#

But this would generally be regarded as a bad idea; in a perfect world there should be no difference

lime schooner
#

In theory they are not the same. operator<< returns an std::ostream& which is not the same as std::cout, but the compiler seems to be able to see through that.

fossil sentinel
lime schooner
#

I still wish compilers would optimize both to std::cout << "12"; minus the length check, but I guess that's too much to ask.

polar owl
polar owl
#

only thing i can think of, is that sometimes i break up very long strings, at common word boundaries, because i think string-pooling optimizations will have to store less static strings in the binary.

meager sageBOT
#

@polar owl Has your question been resolved? If so, run !solved :)

pale veldt
#

the "only" difference is that in one case, for the second << you pass in cout explicitly, and in the other you pass in whatever the previous call gave you

#

that, + one swap around of instructions

#

the "difference" about what stream to use has already been mentioned in text

fossil sentinel
#

Which would mean that to optimise this the compiler would need to be able to prove you haven't modified any of these things