Correct implementation of std::streambuf::overflow

会有一股神秘感。 提交于 2019-12-10 11:24:42

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/20667951/correct-implementation-of-stdstreambufoverflow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!