RE: shared_ptr - implicit conversion to bool
From: wasekvesely
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?
Actually, that's used to prevent mistakes; bool is an integral type, so if you add an implicit conversion to bool, then your smart pointer class can participate in integral promotions. Which allows lots of bad code to compile. :) For an example, implicit conversion to an integral type defines all the comparision operators with any other integral-convertible class. e.g., shared_ptr<int> x; scoped_ptr<int> y; (x == y); // does not do what you might expect... For more information on the problem, see the following reference: More Effective C++, Scott Myers :: Item 28 :: Testing Smart Pointers for Nullness or search the Boost developer archives. -Steve
participants (1)
-
sclearyï¼ jerviswebb.com