I am trying to implement a stream buffer and I'm having trouble with making overflow() work. I resize the buffer by 10 more characters and reset the buffer using setp. Then I increment the pointer back where we left off. For some reason the output is not right:
template <class charT, class traits = std::char_traits<charT>> class stringbuf : public std::basic_stringbuf<charT, traits> { public: using char_type = charT; using traits_type = traits; using int_type = typename traits::int_type; public: stringbuf() : buffer(10, 0) { this->setp(&buffer.front(), &buffer.back()); } int_type overflow(int_type c = traits::eof()) { if (traits::eq_int_type(c, traits::eof())) return traits::not_eof(c); std::ptrdiff_t diff = this->pptr() - this->pbase(); buffer.resize(buffer.size() + 10); this->setp(&buffer.front(), &buffer.back()); this->pbump(diff); return traits::not_eof(traits::to_int_type(*this->pptr())); } // ... std::basic_string<charT> str() { return buffer; } private: std::basic_string<charT> buffer; }; int main() { stringbuf<char> buf; std::ostream os(&buf); os << "hello world how are you?"; std::cout << buf.str(); } When I print the string it comes out as:
hello worl how are ou?
It's missing the d and the y. What did I do wrong?