Something a lot of C++ programmers miss (read: me) when first using stringstreams is the fact that the copy returned by stringstream::str() is a te
How this is done? Looking in the sstream header for libstdc++, I only see a copy being made and returned. How is the lifetime restricted?
str() returns by value, meaning the object it returns is destroyed by the end of the full expression. It's simply the way temporaries work.
Why this is the desired behavior, especially since it is such a common gotcha. If a copy is being made anyway, why can't I take ownership of it?
It's an amendment from the traditional IOStreams. The old deprecated class of streams strstream had an str() method that returned a pointer to its internal buffer. To protect against invalidation of the pointer, the stream had to be "frozen", meaning the buffer could not be resized.
The Standard IOStreams returns a copy of the buffer as a std::basic_string object so that freezing the stream is no longer necessary.