Re: Trying to mimic perl with declarations
From: Jerry Coffin (jcoffin_at_taeus.com)
Date: 03/01/05
- Next message: Jerry Coffin: "Re: how to random no.?"
- Previous message: Martijn Mulder: "Re: Model-View-Controller"
- In reply to: Billy Patton: "Trying to mimic perl with declarations"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 1 Mar 2005 08:39:12 -0800
Billy Patton wrote:
> I need to declare a method with 2 strings as input. one to have a
> default of being empty and not needed to be place in the
> parameters when called.
That's fairly easy to manage.
> The following will compile on a Linux box but get the following when
> executed:
> terminate called after throwing an instance of 'std::logic_error'
> what(): basic_string::_S_construct NULL not valid
> Abort
Hmm...your code really only even compiles more or less accidentally
(i.e. any compiler is required to accept it, but it's mostly an
accidental side-effect).
[ ... ]
> bool x(string& a,string b=NULL);
std::string has a ctor that takes a C-style string (i.e. pointer to
char, expected to have a NUL terminator) as an argument. NULL can stand
in for that pointer, so this compiles, but for the code to work, the
pointer must be non-null.
First of all, I'd code the function to have both parameters as
references to const strings, and then I'd create a unique, empty
std::string object that's used exclusively to initialize the second
parameter. To keep this hidden, I'd personally probably use a class,
and turn x from a function into a functor:
#include <string>
class x {
static const std::string null_string;
public:
bool operator()(std::string const &a,
std::string const &b=null_string);
};
const std::string x::null_string("");
This does a couple of things: since the first argument is a reference
to a const string, you can pass a temporary object, such as passing a
C-style string, letting the compiler create an std::string when needed.
Second, (a rather nice feature) it shouldn't crash! :-) Finally, if you
care to do so, you can distinguish between a default second arguemnt,
and the user having explicitly passed an empty string as the second
argument. I didn't look carefully enough at your function definition to
figure out whether that's useful in this case, but I doubt this is the
only time you'll ever use a default argument, and even if it's not
useful this time, chances are you'll eventually run into a situation
where it is.
--
Later,
Jerry.
The universe is a figment of its own imagination.
- Next message: Jerry Coffin: "Re: how to random no.?"
- Previous message: Martijn Mulder: "Re: Model-View-Controller"
- In reply to: Billy Patton: "Trying to mimic perl with declarations"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|