1

If I open a file and read in a long stream, and I want the data from it, I found out that the following doesn't work, because the str() method of a std::stringstream returns a copy of a temporary that is destroyed as soon as it returns. So the following doesn't work:

std::stringstream ss;
ss << largeFile.rdbuf();
const char* ptr = ss.str().c_str();       // ptr is a dangling pointer

So I actually have to have a temporary std::string for the return of ss.str() to copy to. This ends up (if I understand it correctly), the copy assignment operator of the string class doing a one for one deep copy between the two std::string objects, including the entire buffer it contains. But actually this happening twice because the temporary copy that I discovered gets destructed after ss.str().c_str() returns is also a one for one copy.

I'm a bit confused about this. I'm not great at programming and I was trying to figure out a way to avoid copying big buffers. Thanks.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • 3
    `char* ptr = ss.str();` doesn't compile, since you can't assign a `std::string` to a `char*`. Just use `std::string s = = ss.str();` and rely on copy elision on return. – πάντα ῥεῖ Nov 21 '16 at 15:20
  • @ πάντα ῥεῖ Sorry, I meant char* ptr = ss.str().c_str(); Sorry, mistake. – Zebrafish Nov 21 '16 at 15:22
  • @πάνταῥεῖ I still think you'll end up with 2 buffers no matter what, as `ss` won't be moved from. You have a typo in the comment, 2 equals, but too late to edit it :) – vsoftco Nov 21 '16 at 15:25
  • @vsoftco It's maybe because I made a mistake in the question, I said char* ptr = ss.str() instead of ss.str().c_str(). Obviously in my code that's what I had, I just missed it when asking the question. – Zebrafish Nov 21 '16 at 15:30
  • you might be interested in [this](http://stackoverflow.com/questions/38752936/stream-object-directly-into-a-stdstring) since you're worried about copying large buffers. – jaggedSpire Nov 21 '16 at 15:39

0 Answers0