Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does shared_ptr<> safely allow casting to bool?

Tags:

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?

like image 400
the_mandrill Avatar asked Jul 07 '10 08:07

the_mandrill


People also ask

What is the purpose of the shared_ptr <> template?

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.

Why would you choose shared_ptr instead of Unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

Is shared_ptr reference counting thread safe?

std::shared_ptr is not thread safe. A shared pointer is a pair of two pointers, one to the object and one to a control block (holding the ref counter, links to weak pointers ...).

Should I use shared_ptr or Unique_ptr?

Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.


1 Answers

The technique described in the question is the safe bool idiom.

As of C++11, that idiom is no longer necessary. The modern solution to the problem is to use the explicit keyword on the operator:

explicit operator bool() {   return m_Ptr != nullptr; } 
like image 120
JoeG Avatar answered Oct 24 '22 10:10

JoeG