Boost logo

Boost :

From: Darin Adler (darin_at_[hidden])
Date: 2002-05-08 01:15:22


On Tuesday, May 7, 2002, at 04:41 PM, Rian Mullins wrote:

> I think smart pointers should have an operator bool().
> Many people use the idiom of testing a pointer in an if statement to
> see if it is zero or not, i.e.:
>
> extern MyClass* aPointer ;
> ...
> if( aPointer )
> aPointer->defenestrate() ;
>
> And it would be nice if one could transparently replace a pointer
> type in existing code with a smart_ptr type.
>
> Of course, the implementation would be:
> smart_ptr::operator bool () { return px ; }

Adding an actual operator bool would have the bad side effect of allowing you to use a smart pointer wherever an integer is expected, and turning the pointer into the integer 1. You lose quite a bit of type checking that way.

Some people have developed a "safe_bool" idiom where you define a conversion to an obscure type of pointer (a particularly obscure variant of a pointer to a member) so you can do "if (p)" statements, but not "int i = p" statements. It's used in the Boost function library.

We might want to consider using this technique in the smart pointer library. It's inelegant in implementation, but a lot of people like the "if (p)" idiom.

     -- Darin


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk