Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct implementation of std::streambuf::overflow

Tags:

c++

iostream

I am creating a special std::streambuf and std::ostream implementation. For that I need to implement the std::streambuf::overflow function. The function is protected, only called by std::streambuf::sputc and std::streambuf::xsputn and only when there is no more room in the buffer (that is pptr() == epptr()). The default behaviour is to return eof, so it is obviously not correct to call the function in place of sputc.

Nevertheless both GNU libc implementation of std::stringbuf and boost implementation of boost::io::alt_stringbuf in Boost.Format still check whether pptr() < epptr() and such case simply append the character. In the later case even daringly by calling sputc (and thus relying on the fact that it will not call overflow if there is still room in the buffer).

What is the reason to implement this case?

Ok, I don't really understand the other case, overflow(eof()), either. It does not appear to be actually used anywhere though it is explicitly specified.

like image 442
Jan Hudec Avatar asked Mar 28 '26 10:03

Jan Hudec


1 Answers

The question seems to be why implementation check if this->pptr() == this->epptr(): the simple reason is that a further derived class might end up calling the protected function! The standard C++ library will never call overflow() when there is space in the buffer. For some time I used to also check whether this->pptr() == this->epptr() but I have stopped doing so: the implicit contract is that further derived class don't do silly things.

The other question raised is: what does it mean for overflow() to be called with the argument traits_type::eof()? Although I keep handling this case it is another case which doesn't happen from within the standard C++ library: the intention is to have overflow() flush the stream. That is, sync() would just call this->overflow(traits_type::eof()). In practise I found it more reasonable to call sync() from overflow() probably after storing the character into the buffer (i.e., sync() woube called with pptr() == epptr() + 1 which, of course, assumes that the allocated buffer has space for at least one more character).

like image 151
Dietmar Kühl Avatar answered Mar 29 '26 23:03

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!