1

I can copy some ostringstream into a new char array like this:

std::ostringstream stream;
...

std::string str = stream.str();
size_t size = str.size();

char *target = new char[size];
memcpy(target,str.c_str(),size);

How about the performance? Is there a way to copy the data directly to the array Buffer?

I think it will look like:

size_t size = str.tellp();
char *target = new char[size];
stream.copyTo(target,size); //??
powerpete
  • 2,663
  • 2
  • 23
  • 49
  • 4
    You can always use the `std::string` directly. You don't have to copy out of it to use it as a C string (at least in C++11, where it has guaranteed contiguous storage). – chris Dec 12 '17 at 16:53
  • The would be fine. But I need an char array (created with new char[]) in an other function. – powerpete Dec 12 '17 at 17:02
  • 1
    A `std::string`essentially already contains that. There's a [good answer](https://stackoverflow.com/a/14291203/962089) on how to get at it for modification. It also turns out that C++17 added a non-const version of `data()` to give direct write access. – chris Dec 12 '17 at 17:15
  • 1
    If you want to avoid any copying at all, you have to get access to the array that gets used by the stream buffer. A possible approach would be implementing a custom streambuffer and giving that one to the stream, like being done [here](https://artofcode.wordpress.com/2010/12/12/deriving-from-stdstreambuf/). – Jodocus Dec 12 '17 at 17:17
  • As far as array-backed streams go, there's `std::strstream`, which is deprecated, and [`std::spanstream`](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0448r0.pdf), which progressed to LWG at the last meeting, so it might be in C++20. – chris Dec 12 '17 at 17:31

0 Answers0