Boost logo

Boost :

From: Persson Jonas (jonas.persson_at_[hidden])
Date: 2002-05-08 04:31:40


> 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

Another possibility is to disable implicit conversion by
declaring another integer operator:

class X {
public:
 ...
  operator bool () { return px ; }
private:
  operator char ();
};

or am I missing some obvious drawback of this solution?

        / Jonas


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