shared_ptr - implicit conversion to bool

Hi, I've found this in "shared_ptr.hpp": // implicit conversion to "bool" typedef T * (this_type::*unspecified_bool_type)() const; operator unspecified_bool_type() const // never throws { return px == 0? 0: &this_type::get; } Why this is better than: operator bool() const { return px != 0; } What more can I do with somethin like this? Thank you, Wasek

"wasekvesely
Hi,
I've found this in "shared_ptr.hpp":
// implicit conversion to "bool" typedef T * (this_type::*unspecified_bool_type)() const;
operator unspecified_bool_type() const // never throws { return px == 0? 0: &this_type::get; }
Why this is better than:
operator bool() const { return px != 0; }
What more can I do with somethin like this?
It's not that you can do more; quite the opposite. int f(long); int x = f(shared_ptr<int>()); // error With operator bool(), that (and many other abuses) would compile. -- David Abrahams dave@boost-consulting.com * http://www.boost-consulting.com Boost support, enhancements, training, and commercial distribution

From: "David Abrahams"
"wasekvesely
" writes: I've found this in "shared_ptr.hpp":
// implicit conversion to "bool" typedef T * (this_type::*unspecified_bool_type)() const;
operator unspecified_bool_type() const // never throws { return px == 0? 0: &this_type::get; }
Why this is better than:
operator bool() const { return px != 0; }
What more can I do with somethin like this?
It's not that you can do more; quite the opposite.
int f(long); int x = f(shared_ptr<int>()); // error
With operator bool(), that (and many other abuses) would compile.
Yeah. It's the same reason that stream classes has an implicit conversion to pointer, to give a bool value regarding its state. With an implicit conversion to bool, you could have done nonsensical things like the above example, and e.g.: int value=cin+cin; // Would compile! Instead, using the current definition, you may do: delete cin; // (!) This is fixed in shared_ptr, though, so you can't do that, either. Regards, Terje
participants (3)
-
David Abrahams
-
Miko
-
wasekvesely <vaclav.vesely@volny.cz>