Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to move the .str() member of a stringstream?

Tags:

Consider the following example:

#include <sstream>
template <typename T>
inline std::string to_string(T const & op) {
    std::ostringstream result;
    result << op;
    return result.str();
}

If I was to return result, instead of result.str() it would automatically become an rvalue. Not so the string contained in in result (I assume). My expectation is that it is copied and the copy returned as an rvalue.

So my question here is, is it legal to:

return std::move(result.str());

I would assume it is, expecting the stream to be left with a valid, empty string. But I do not feel certain enough to actually do it.

like image 266
kamikaze Avatar asked Mar 01 '16 15:03

kamikaze


1 Answers

std::ostream::str indeed returns a copy of the internal string. So the move is legal, but it makes no sense as result.str() is an rvalue anyway and thus the std::move does nothing useful. If anything, it hinders RVO, so don't do it. (As @TartanLlama correctly pointed out in their comment, "Don't move the return value" holds true in general, not just when returning rvalues.)

In particular, the std::move does not affect the internal string object of the stream.

like image 182
Baum mit Augen Avatar answered Oct 25 '22 00:10

Baum mit Augen