简体   繁体   中英

std::stringstream.str() is always the same string being returned?

When creating a std::stringstream and filling it with data, can I rely on the same string object being returned as long as the stream is not changed anymore?

To illustrate what I mean, consider this example:

std::stringstream ss;

ss << value1;
ss << value2;
...

std::vector<char> data(ss.str().begin(), ss.str().end());

Now in the case of the vector being filled, is this valid or will stringstream always create a new string object?

So would it be better/safer/correct to do it like this and have an additional copy operation?

std::string s = ss.str();
std::vector<char> data(s.begin(), s.end());

The documentation is your friend. Use it!

std::basic_stringstream::str() returns by value (ie a copy), so what you're doing is not safe.

You could create your own local as in your example (and rely on RVO), or you could bind the result to a ref-to- const :

const std::string& s = ss.str();
std::vector<char> data(s.begin(), s.end());

Your second attempt is correct (and probably the best you can really do, if we are using string streams).

As for the first attempt... That isn't valid, as far as I can tell. This site http://www.cplusplus.com/reference/sstream/stringstream/str/ says:

string str() const;

Which means it returns a new string by value.

If it returned a string&, you'd get away with it.

You also asked "So would it be better/safer/correct to do it like this and have an additional copy operation?"

but you may have overlooked the fact that both "ss.str" calls would allocate a new string each time.

It's a shame that there's no obvious way to get a vector out of a stringstream (without going via a string).

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