From: Francis Glassborow on
Alex Strickland wrote:
> Francis Glassborow wrote:
>
>>> // trim from both ends
>>> static inline std::string & trim( std::string & s ) {
>>> return ltrim( rtrim( s ) );
>>> }
>
>> It isn't just a warning but identifies a genuine error in your code.
>
> Thank you. I have changed the above to:
>
> static inline std::string & trim( std::string s ) {
>
> Compiles and works, but doesn't seem optimal?


but now your return is referring to a local variable.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: AnonMail2005 on
On Dec 17, 7:46 pm, Alex Strickland <s...(a)mweb.co.za> wrote:
> Francis Glassborow wrote:
> >> // trim from both ends
> >> static inline std::string & trim( std::string & s ) {
> >> return ltrim( rtrim( s ) );
> >> }
> > It isn't just a warning but identifies a genuine error in your code.
>
> Thank you. I have changed the above to:
>
> static inline std::string & trim( std::string s ) {
>
> Compiles and works, but doesn't seem optimal?
>
> Regards
> Alex
That's because I think your function signature is somewhat unatural.
For string manipulation functions, either a take a non const reference
to a string as an argument and modify the argument or take const
reference to a string and pass the result back as the return value.
Make your function signature consistantly one or the other (not both).

So the trim signature would be one of these:
a. void trim(std::string & s)
b. std::string trim(const std::string & s)

Take a look at the standard library string functions and boost string
manipulation libraries for guidance on defining function signatures.
I prefer the latter signature but that's just a personal preference.

HHT


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Jonathan Lee on
On Dec 17, 7:46 pm, Alex Strickland <s...(a)mweb.co.za> wrote:
> Compiles and works, but doesn't seem optimal?

How about:

#include <string>
#include <functional>
#include <cctype>
#include <iostream>
#include <algorithm>

using namespace std;

static unary_negate< pointer_to_unary_function<int, int> >
notspace = not1(ptr_fun<int, int>(isspace));

string ltrim(const string & s ) {
return string(find_if(s.begin(), s.end(), notspace), s.end());
}

int main() {
string a(" Here ");
cout << ltrim(a) << ':' << endl;
return 0;
}

--Jonathan


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]