Article Discussion
The Safe Bool Idiom
Summary: Learn how to validate objects in a boolean context without the usual harmful side effects.
18 posts on 2 pages.      
« Previous 1 2 Next »
The ability to add new comments in this discussion is temporarily disabled.
Most recent reply: October 13, 2010 11:04 AM by Joe
Ian
Posts: 3 / Nickname: codic / Registered: August 26, 2004 3:49 PM
Re: The Safe Bool Idiom
September 3, 2004 5:54 PM      
> Have you looked at Java since 1.0? The nio package
> provides access to using native select() or poll()
> implementations on socket and file streams.

Hey, lookie there! I googled for this a couple months ago and found nothing (except a few people saying it couldn't be done). Must have been using crappy search criteria.

> But, that is more of that confusing syntax stuff that
> doesn't provide the user with any good sub-conscience
> glue. Making users type obj1.equals( obj2 ) is not a bad
> thing either...

I wouldn't call the "address of" operator confusing, but it's all a matter of opinion.

> Would be
> interesting to see how that would be implemented without
> == being assigned to a member method to begin with.

The compiler writers have managed to do it with implicitly defined operator= and copy constructors. I don't think it's too much of a stretch to apply similar member traversal logic to equality comparisons, but aparently some one did. Perhaps the answer lies in the ARM.



Well, shame on me for not knowing my tools. I obviously don't know either language well enough to effectively argue the finer points of either one in a public forum.

But I do know that you use the right tool for the right job. Sometimes the right tool is C++ (like it or not), and articles like this make better programmers out of all of us.

ian.
Victor
Posts: 1 / Nickname: sekmu / Registered: March 30, 2009 1:59 PM
Re: The Safe Bool Idiom
March 30, 2009 7:19 PM      
A word of warning, and a question for if anyone has encountered and/or has a solution for this issue (other than the obvious "don't allow this code").

If you (already) have an explicit conversion to a pointer type other than bool_type, the compiler may very well choose the non-bool_type, resulting in unexpected behavior.

example crashy:

class Testable
{
private:
Thing *mData;

public:
typedef void (xOGModelRefPtr::*bool_type)() const;
void type_does_not_support_comparisons() const {}
operator bool_type() const
{
return (mData && mData->IsValid()) ? Testable::type_does_not_support_comparisons : NULL;
}

Testable() : mData(NULL) {}
operator Thing*() const { return mData->mPtr; }
};

void fn(Thing *);
void main()
{
Testable t;
if(t) // crash on access of null mData->
fn(t);
}

Joe
Posts: 1 / Nickname: joem / Registered: October 13, 2010 6:02 AM
Re: The Safe Bool Idiom
October 13, 2010 11:04 AM      
Is this code copyright restricted? Is there a license for reuse of this code?
18 posts on 2 pages.
« Previous 1 2 Next »