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.