|
Boost : |
From: Darin Adler (darin_at_[hidden])
Date: 1999-12-27 02:46:06
> 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 thing,
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 bad
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())
myself. Of course, I have a bigger hang-up about null pointers, as readers
of this list may already know. I just can't stand the fact that:
C* x;
means that x points to an object of class C and you can use all the members
declared in class C, unless it's 0, in which case you can't use *any* of the
members declared in class C! It's just a gaping hole in the type system.
-- Darin
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk