On 8/22/2010 9:38 PM, Daniel Pitts wrote:
Yes, actually there is. If the string consists only of spaces, it ends
up construction std::string tmp(str.end(), str.rend()) and it will most
likely start reading memory it shouldn't.
Yes. I remember having looked at this problem in the past. You
need to save the intermediate result, in order to use it as the
end criterion for the second search, e.g.:
struct is_space_p : std::unary_function<char, bool>
{
bool operator()( char ch ) const
{
return isspace( static_cast<unsigned char>( ch ) ) != 0;
}
};
std::string
trim( std::string const& original )
{
std::string::const_iterator end
= std::find_if(original.rbegin(), original.rend(),
std::not1(is_space_p())).base();
return std::string(
std::find_if(original.begin(), end, std::not1(is_space_p())),
end);
}
(Of course, this still fails if the original is encoded in
UTF-8.)
Constructing the result in a temporary so that if it something
does throw, the state of the argument is unchanged is a good
idea though.
Using an inout argument to begin with probably isn't a good
idea. Better to return the string as above. (Alternatively,
you can overload, providing a second version:
void trim( std::string* text )
{
*text = trim( *text );
}
But the form returning the string should be the primary
version.)