Christopher Smith on Wed, 5 May 2004 20:58:26 -0500 (CDT)


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [ALACPP] const char* NULL to std::string api


On Wed, 2004-05-05 at 16:46, Gavin Doughtie wrote:
> So an interesting puzzle came up at work today.
> 
> Say you have an API like so:
> 
> void doFoo(const char* param)
> {
> 	if (NULL != param) {
> 		// do something
> 	}
> }
> 
> Great. Now say you want to be modern and write the api like so:
> 
> void doFoo(const std::string& param)
> {
> }
> 
> Now imagine that somebody calls you with a NULL const char* param. std::string tries to implicitly convert that NULL pointer to a std::string,
> and, if you are lucky and your compiler isn't a leftover from the tech boom like it might be at certain entertainment companies, the string constructor
> throws a logic_error.

This would seem like correct behavior to me. Contractually,
"const std::string&" doesn't allow for a null value to be passed, and
logic_error is about the kind of exception I'd expect from that
scenario. This is the kind of thing that I *like* about the "modern"
interface, as it avoids me having to write special case code for null
string pointers.

If you are hell bent on supporting the old behavior. I'd be tempted to
do something like this:

//Silly doFoo() guard that swallows the exception
//We could just test for null here, but I'm annoyed
//by the thought of doing it on top of the check
//done int the STL
inline void doFoo(const char* param) {
    try {
	doFoo(param);
    } catch (std::logic_error&) {
        //nothing, because for some silly reason we think
	//this is okay behavior
    }
}

void doFoo(const std::string& param);

> The best I've come up with so far is some nasty boost::preprocessor macro to write the parellel implementation for you. Does anybody have a better idea?

If null really *is* a valid value, then really the interface should be:

void doFoo(const std::string* param);

That will of course mean that all the callers will have to be changed,
but it'd be the right thing to do.

-- 
Christopher Smith <x@xxxxxxxx>
_______________________________________________
alacpp mailing list
alacpp@xxxxxxxxxxx
http://lists.ellipsis.cx/mailman/listinfo/alacpp