Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::stringstream efficient way to get written data, copy to another stream

Tags:

c++

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.

like image 532
edA-qa mort-ora-y Avatar asked Nov 02 '10 13:11

edA-qa mort-ora-y


1 Answers

Use boost::interprocess::vectorstream or boost::interprocess::bufferstream. These classes basically meet all of your requirements.

boost::interprocess::vectorstream won't return a const 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::bufferstream will 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 a char buffer 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.

like image 100
Charles Salvia Avatar answered Nov 06 '22 12:11

Charles Salvia