I have some existing code that uses a std::ostringstream as an temporary buffer. To increase robustness, I want to define an upper limit for the buffer size (e.g., 16 KB). When the limit is exceeded, all following data that is append, should be silently discarded. Ideally, after logging a warning.
What is the simplest way of doing it? std::ofstream seems to have no efficient way of getting its current size. I can only think of my_stream.str().size(), which seems to be highly inefficient.
Of course, I can manually keep track of the number of inserted chars by keeping an extra counter, but maybe there is an elegant alternative that I am missing. I saw that ofstringstream has an internal buffer (rdbuf()) that can be replaced.
Is it possible (and practical) to use it to solve my problem?
One possible solution is to extend stringbuf into your own class and use that within
ofstringstream. Then it should be trivial to implement your max limit. It looks likestringbuf::overflowis the function you want to overload.Alternatively you could wrap the
std::ostringstreamwithin another class which checkssizebefore writing to it. How do you conclude that this is inefficient? As long as the size is not calculated every call, it is just the matter of navigating down the indirection.Edit: Missed the word “copy” in the reference, but yes, once you wrap it, you could keep your own counter.
Alternatively, you could use
tellpto try and figure out how many characters are written, as long as it always points to the end.