The first thing to not is that you are deriving from std::basic_stringbuf<char>
for whatever reason without overriding all of the relevant virtual functions. For example, you don't override xsputn()
or sync()
: whatever these functions end up doing you'll inherit. I'd strongly recommend to derive your stream buffer from std::basic_streambuf<char>
instead!
The overflow()
method announces a buffer which is one character smaller than the string to the stream buffer: &buffer.back()
isn't a pointer to the end of the array but to the last character in the string. Personally, I would use
this->setp(&this->buffer.front(), &this->buffer.front() + this->buffer.size());
There is no problem so far. However, after making space for more characters you omitted adding the overflowing character, i.e., the argument passed to overflow()
to the buffer:
this->pbump(diff);
*this->pptr() = traits::to_char_type(c);
this->pbump(1);
There are a few more little things which are not quite right:
- It is generally a bad idea to give overriding
virtual
functions a default parameter. The base class function already provides the default and the new default is only picked up when the function is ever called explicitly. The string returned may contain a number of null characters at the end because the held string is actually bigger than sequence which was written so far unless the buffer is exactly full. You should probably implement the
str()
function differently:std::basic_string<charT> str() const { return this->buffer.substr(0, this->pptr() - this->pbase()); }
- Growing the string by a constant value is a major performance problem: the cost of writing
n
characters isn * n
. For largern
(they don't really need to become huge) this will cause problems. You are much better off growing yourbuffer
exponentially, e.g., doubling it every time or growing by a factor of1.5
if you feel doubling isn't a good idea.