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); //??
5
  • 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). Commented Dec 12, 2017 at 16:53
  • The would be fine. But I need an char array (created with new char[]) in an other function. Commented Dec 12, 2017 at 17:02
  • 1
    A std::stringessentially already contains that. There's a good answer 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. Commented Dec 12, 2017 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. Commented Dec 12, 2017 at 17:17
  • As far as array-backed streams go, there's std::strstream, which is deprecated, and std::spanstream, which progressed to LWG at the last meeting, so it might be in C++20. Commented Dec 12, 2017 at 17:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.