Without writing a custom rdbuf is there any way to use a stringstream efficiently? That is, with these requirements:
- the stream can be reset and writing start again without deallocating previous memory
- get a const char* to the data written (along with the length) without creating a temporary
- populate the stream without creating a temporary string
If somebody can give me a definitive “no” that would be great.
Now, I also use boost, so if somebody can provide a boost alternative which does this that would be great. It has to have both istream and ostream interfaces available.
Use
boost::interprocess::vectorstreamorboost::interprocess::bufferstream. These classes basically meet all of your requirements.boost::interprocess::vectorstreamwon’t return aconst char*, but it will return a const reference to an internal container class, (like an internal vector), rather than returning a temporary string copy. On the other hand,boost::interprocess::bufferstreamwill basically allow you to use any arbitrary buffer as an I/O stream, giving you complete control over memory allocation, so you can easily use acharbuffer if you want.These are both great classes, and wonderful replacements for
std::stringstream, which, in my opinion, has always been hindered by the fact that it doesn’t give you direct access to the internal buffer, resulting in the unnecessary creation of temporary string objects. It’s a shame these classes are somewhat obscure, hidden away in the interprocess library.