简体   繁体   中英

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

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.

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 his 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM