Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: Jason McKesson Newsgroups: comp.std.c++ Subject: Move semantics in stringstream Date: Sun, 26 Feb 2012 08:04:57 -0800 (PST) Organization: unknown Lines: 49 Sender: std-cpp-request@vandevoorde.com Approved: stephen.clamage@oracle.com Message-ID: <4F47EAC8.2040608@gmail.com> References: <4F47E9AD.3030001@gmail.com> NNTP-Posting-Host: 4G3Xgxs1BYLoODYLuYqReTCAMmyB4Z4xmoymjzayz+0= Content-Type: text/plain; charset=ISO-8859-1; format=flowed X-Trace: news.albasani.net PK0g3U7SshID1SUCBnbHUxJAqCU0GEHjlOanGUvJKv/otdN/vjYQS75SFbfXtmlmb9hiBNsDrfHK3PApA9SkEA== X-Complaints-To: abuse@albasani.net NNTP-Posting-Date: Sun, 26 Feb 2012 16:08:19 +0000 (UTC) X-Mailer: Perl5 Mail::Internet v2.05 X-Submission-Address: std-cpp-submit@vandevoorde.com Cancel-Lock: sha1:4Vf+nMJi7wC1JZQLCeA5WZSWElE= X-Original-Date: Fri, 24 Feb 2012 11:53:44 -0800 Xref: x330-a1.tempe.blueboxinc.net comp.std.c++:421 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 ]