Boost logo

Boost :

From: Jon Jagger (Jon.Jagger_at_[hidden])
Date: 1999-12-27 04:05:27

> Well, this begs the question: why not add an operator bool() method to
> shared_ptr and scoped_ptr?

Unfortunately, operator bool() doesn't work too well for this kind of
due to the integer promotion rules. Here's an example of the problem:

    void f(boost::scoped_ptr<int> p)
        int x = p; // Ooops! Converted a pointer to a 0 or a 1!

To work around this, some classes in the C++ standard instead provide
conversion to void*, which work inside if statements, but don't have the
effect above. The void* conversion is still a bit dangerous and can be used
by accident when assigning to a void* for example. There are
more-sophisticated versions of the void* conversion trick (like "const
volatile incomplete*"), but I don't know of one that's perfect.

I consider this an unfortunate mistake in the design of bool. The implicit
conversion from bool to int isn't so valuable. But I think it's too late to
complain about this.

> If the goal is to "mimic a built-in pointer", then an operator bool()
> conversion would make sense. It seems that using get() should be
> avoided whenever possible, as it could be dangerous to let people play
> with the _real_ pointer as long as reference-counted version exists.

Something like the void* trick, or a null() or is_null() member function
would be an improvement. I don't like:

    if (p.get())

     Just a thought.... wouldn't something like this work as you want?

     template<typename type>
     class scoped_ptr
          operator bool() const;
          operator !() const;
          operator int() const;

     Jon Jagger

Boost list run by bdawes at, gregod at, cpdaniel at, john at