Accessing the associated string of a stringstream object
I am trying to access the associated string of a stringstream object and keep iterators to it, but am not able to know whether this would be safe. Here is the code :
stringstream HTMLss; // string stream of HTML document
// ... (load up HTMLss with HTML)
const string & HTMLstr = HTMLss.str(); // grab reference to associated string
string::const_iterator begin,end;
begin = HTMLstr.begin(); // grab iterators to that string as well
end = HTMLstr.end();
boost::match_results<std::string::const_iterator> matches;
// do开发者_运维知识库 some processing, updating the iterators along the way
while( boost::regex_search(begin, end, matches, metaexp) )
{
string key( matches[1].first, matches[1].second );
string raw_val( matches[2].first, matches[2].second );
// ... some processing which does NOT manipulate HTMLss stringstream in any way
begin = matches[2].second; // updating the iterator
}
My question is -- is the above safe to do ? Can it be assumed that one can keep/update iterators that point to the associated string of the stringstream object, and that the behavior is going to be correct? There are no other calls to any string stream function. How can one know whether this is safe or not?
Take a closer look at stringstream's str method. It returns a copy of the string, not a reference to a string object. So in theory, as long as you, yourself do not change the string your iterators won't be invalidated.
It's safe but for a another reason than you probably think. HTMLss.str()
returns a copy of the internal string, and this copy is bound to a const reference. As per C++ rules a temporary that is bound to a local const reference has the lifetime of the reference. So basically the code you posted is almost equivalent to this:
string HTMLstr = HTMLss.str();
The only difference is that this version may call the copy constructor. This call may be optimized away though.
This returns a temporary which is lifetime-extended to HTMLstr's scope:
const string & HTMLstr = HTMLss.str();
Because this is a copy of HTMLss's buffer, any later changes made to HTMLss won't be reflected, but it's perfectly find to keep and use iterators to HTMLstr for as long as HTMLstr is in scope.
However, you might as well make HTMLstr a non-reference, but you can keep the const (or drop it) as you like:
const string HTMLstr = HTMLss.str();
Keeping the const does reduce the ways you can invalidate the iterators, but you didn't have a problem with that in the original code either.
精彩评论