Consider the following code:
class C{};
std::ostream &operator <<(std::ostream &o, const C &) {
o.fill('!');
o.width(8);
return o << 42;
}
int main() {
std::cout << C{} << '\n';
std::cout << 42 << '\n';
return 0;
}
It outputs:
!!!!!!42
42
I was expecting !!!!!!42
twice because I've changed the state of the provided std::ostream o
calling fill
and width
inside the operator <<
, so I used to think that the fill character and the width setted into the operator would leak outside the operator call as if they were sticky properties.
As you can see I don't flush the stream nor re-set the fill character or width so, why (and how) the original behaviour is preserved?
So the question is: How the properties of the ostream
are setted back to the previous state after the call to my operator<<
for class C
?
This doesn't bothers me, I'm happy with this behaviour but I want to understand how it works.