Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Jason McKesson<jmckesson@gmail.com> |
|---|---|
| Newsgroups | comp.std.c++ |
| Subject | Move semantics in stringstream |
| Date | 2012-02-26 08:04 -0800 |
| Organization | unknown |
| Message-ID | <4F47EAC8.2040608@gmail.com> (permalink) |
| References | <4F47E9AD.3030001@gmail.com> |
strstream is very useful. In C++98/03, it was useful because it avoided
unneeded copies of strings. For example:
std::ostringstream out_data;
out_data<< ...;
std::string my_data = out_data.str();
The last line causes a copy, rather unnecessarily, since this function
is now done with out_data.
By contrast, we can do this with strstream:
char buffer[1000];
std::ostrstream out_data(buffer, 1000);
out_data<< ...;
This requires no copying of the data. Obviously the string is a char*
rather than a std::string, but we at least have the data without a copy.
In C++11, we have move semantics. So the copying is completely
unnecessary from a language point of view. Sadly, the API was not
properly updated to match.
What we need is for std::stringbuf and the corresponding functions in
the stringstream classes to be able to have a string moved into them.
Also, they should be able to have their contents removed without a copy.
So it would look something like this:
std::stringstream out_data{std::move(some_string)};
out_data<< ...;
std::string my_data = out_data.move_str();
Where move_str() will actually steal the string from the stream. No
string data is ever copied here. move_str should properly invalidate the
stream, as if the user had moved from the stream itself.
The current constructor of std::stringbuf, and the associated
stringstream classes, take a `const&` to a basic_string. They should
take their string argument by value (thus copying when movement is not
allowed) and simply move it to where it needs to go. If that is not
possible due to backwards compatibility issues, then it can take an
r-value reference instead of a value.
--
[ comp.std.c++ is moderated. To submit articles, try posting with your ]
[ newsreader. If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Back to comp.std.c++ | Previous | Next — Next in thread | Find similar | Unroll thread
Move semantics in stringstream Jason McKesson<jmckesson@gmail.com> - 2012-02-26 08:04 -0800 Re: Move semantics in stringstream Daniel Krügler <daniel.kruegler@googlemail.com> - 2012-03-04 14:23 -0800
csiph-web