Pregunta

As an easy way to store several status logs etc. I have chosen a std::stringstream. In case of an error I can simply dump .rdbuf() into a file to be able to reproduce what my program has been doing before it crashed.

My problem now is, that this stringstream grows in size indefinitely. I have tried several things to ensure that I only keep the last 1MiB or so of the stream but have not been successful.

  1. .rdbuf()->pubseekoff(...)
  2. .ignore(...)
  3. getline(...)
  4. ss.str() = ss.str().substr(...)

Apparently the underlying buffer object always only increases in size - no matter whether some of the data has already been read or not.

Is there any way to reduce the size / hold it at some constant (preferably without regular deep copies)? A circular buffer as an underlying buffer object would be perfect - is that possible? Esp. does that already exist?


EDIT: The solution basically has to behave like a stream. It is placed by the procompiler instead of std::err or a direct filestream (similar to the boost::log). It is therefore not strictly necessary, but very useful to use a stringstream. (Otherwise I would have to implement all the ostream stuff to be able to stream std::endl...)

¿Fue útil?

Solución

On my current STL implementation (VS2010 SP1), str("") releases all memory

std::stringstream ss;
for(unsigned int i = 0; i<10000000; ++i)
{
    ss << "QWERTYUIOPASDFGHJKLXCVBNM";
}

ss.str(""); // memory released here

Reference: "Internally, the function calls the str member of its internal string buffer object."

I interpret that sentence to mean that if I assign an empty string, it'll copy-construct the underlying buffer to that.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top