Alex Rivera | Logout

How does shared_ptr<> safely allow casting to bool?

Asked 2010-07-07T08:43:24.927
21

I was looking into how std::tr1::shared_ptr<> provides the ability to cast to bool. I've got caught out in the past when trying to create a smart pointer that can be casted to bool as the trivial solution, ie

operator bool() {
  return m_Ptr!=0;
}

usually ends up being implicitly castable to the pointer type (presumably by type promotion), which is generally undesirable. Both the boost and Microsoft implementations appear to use a trick involving casting to an unspecified_bool_type(). Can anyone explain how this mechanism works and how it prevents implicit casting to the underlying pointer type?

Edit
Report

1 Answer

3

Usually what it returns is a member pointer. Member pointers can be treated like a bool but don't support many of the implicit conversions which bool does.

answered 2010-07-07T08:45:36.780

Your Answer