
Hi, The following code is excerpted from Boost.Function. I just don't unstanding it. Why use "safe_bool"? What's the advantage? Can any one explain it to me? Thanks. // code from <boost/function/function_base.hpp> // ===> private: struct dummy { void nonnull() {}; }; typedef void (dummy::*safe_bool)(); public: operator safe_bool () const { return (this->empty())? 0 : &dummy::nonnull; } safe_bool operator!() const { return (this->empty())? &dummy::nonnull : 0; } // code from <boost/function/function_base.hpp> // <===

From: <mr_lilirong@yahoo.com>
The following code is excerpted from Boost.Function. I just don't unstanding it. Why use "safe_bool"? What's the advantage? Can any one explain it to me?
Thanks.
// code from <boost/function/function_base.hpp> // ===>
private: struct dummy { void nonnull() {}; };
typedef void (dummy::*safe_bool)();
public: operator safe_bool () const { return (this->empty())? 0 : &dummy::nonnull; }
safe_bool, as its name implies, is a safer type to use in implicit conversions when you need your type to act as a bool, like in if(f) Using an operator bool() - since a bool can be converted to int - means that any arithmetic expression that contains 'f' will compile, like f == 5 f + 2 f >> 1 etc Using 'operator void const * () const', as std::cin and std::cout do, is a bit better, but it still allows some unfortunate side effects: if(std::cin == std::cout) delete std::cin; Using a member pointer avoids most of these pitfalls leaving only comparisons valid. They are specifically disabled in boost::function. -- Peter Dimov Multi Media Ltd.

Thank you very much. Now I understand it. --- In Boost-Users@y..., "Peter Dimov" <pdimov@m...> wrote:
From: <mr_lilirong@y...>
The following code is excerpted from Boost.Function. I just don't unstanding it. Why use "safe_bool"? What's the advantage? Can any one explain it to me?
Thanks.
// code from <boost/function/function_base.hpp> // ===>
private: struct dummy { void nonnull() {}; };
typedef void (dummy::*safe_bool)();
public: operator safe_bool () const { return (this->empty())? 0 : &dummy::nonnull; }
safe_bool, as its name implies, is a safer type to use in implicit conversions when you need your type to act as a bool, like in
if(f)
Using an operator bool() - since a bool can be converted to int - means that any arithmetic expression that contains 'f' will compile, like
f == 5 f + 2 f >> 1
etc
Using 'operator void const * () const', as std::cin and std::cout do, is a bit better, but it still allows some unfortunate side effects:
if(std::cin == std::cout) delete std::cin;
Using a member pointer avoids most of these pitfalls leaving only comparisons valid. They are specifically disabled in boost::function.
-- Peter Dimov Multi Media Ltd.
participants (2)
-
mr_lilirong@yahoo.com
-
Peter Dimov