Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Copying string from ostringstream

Tags:

I have a named std::string that I want to fill with data via an std::ostream interface and avoid a string copy.
One way to do it which does involve a copy is to do this:

bool f(std::string& out)
{
   std::ostringstream ostr;
   fillWithData(ostr);
   out = ostr.str(); // 2 copies here
   return true;
}

I need to pass the result through out and cannot return ostr.str().
I want to avoid the copies in out = ostr.str(); since this string may be very big.

Is there some way, maybe using rdbuf()s, to bind the std::ostream buffer directly to out?

To clarify, I am interested in the auto-expanding behaviour of std::string and std::ostream so that the caller does not have to know the size before the call.

UPDATE: I just realized that the innocuous line out = ostr.str(); will probably entail 2 copies:

  1. The first by the str() call
  2. The other by the std::string assignment operator.