Ok, so the last time I wrote C++ for a living, std::auto_ptr
was all the std lib had available, and boost::shared_ptr
was all the rage. I never really looked into the other smart pointer types boost provided. I understand that C++11 now provides some of the types boost came up with, but not all of them.
So does someone have a simple algorithm to determine when to use which smart pointer? Preferably including advice regarding dumb pointers (raw pointers like T*
) and the rest of the boost smart pointers. (Something like this would be great).
Shared ownership:
The
shared_ptr
andweak_ptr
the standard adopted are pretty much the same as their Boost counterparts. Use them when you need to share a resource and don't know which one will be the last to be alive. Useweak_ptr
to observe the shared resource without influencing its lifetime, not to break cycles. Cycles withshared_ptr
shouldn't normally happen - two resources can't own each other.Note that Boost additionally offers
shared_array
, which might be a suitable alternative toshared_ptr<std::vector<T> const>
.Next, Boost offers
intrusive_ptr
, which are a lightweight solution if your resource offers reference-counted management already and you want to adopt it to the RAII principle. This one was not adopted by the standard.Unique ownership:
Boost also has a
scoped_ptr
, which is not copyable and for which you can not specify a deleter.std::unique_ptr
isboost::scoped_ptr
on steroids and should be your default choice when you need a smart pointer. It allows you to specify a deleter in its template arguments and is movable, unlikeboost::scoped_ptr
. It is also fully usable in STL containers as long as you don't use operations that need copyable types (obviously).Note again, that Boost has an array version:
scoped_array
, which the standard unified by requiringstd::unique_ptr<T[]>
partial specialization that willdelete[]
the pointer instead ofdelete
ing it (with thedefault_delete
r).std::unique_ptr<T[]>
also offersoperator[]
instead ofoperator*
andoperator->
.Note that
std::auto_ptr
is still in the standard, but it is deprecated.§D.10 [depr.auto.ptr]
No ownership:
Use dumb pointers (raw pointers) or references for non-owning references to resources and when you know that the resource will outlive the referencing object / scope. Prefer references and use raw pointers when you need either nullability or resettability.
If you want a non-owning reference to a resource, but you don't know if the resource will outlive the object that references it, pack the resource in a
shared_ptr
and use aweak_ptr
- you can test if the parentshared_ptr
is alive withlock
, which will return ashared_ptr
that is non-null if the resource still exists. If want to test whether the resource is dead, useexpired
. The two may sound similar, but are very different in the face of concurrent execution, asexpired
only guarantees its return value for that single statement. A seemingly innocent test likeis a potential race condition.
Cases of when to use
unique_ptr
:Cases of when to use
shared_ptr
:Cases of when to use
weak_ptr
:Feel free to edit and add more
Deciding what smart pointer to use is a question of ownership. When it comes to resource management, object A owns object B if it is in control of the lifetime of object B. For example, member variables are owned by their respective objects because the lifetime of member variables is tied to the lifetime of the object. You choose smart pointers based on how the object is owned.
Note that ownership in a software system is separate from ownership as we would think of it outside of software. For example, a person might "own" their home, but that doesn't necessarily mean that a
Person
object has control over the lifetime of aHouse
object. Conflating these real world concepts with software concepts is a sure-fire way to program yourself into a hole.If you have sole ownership of the object, use
std::unique_ptr<T>
.If you have shared ownership of the object...
- If there are no cycles in ownership, use
std::shared_ptr<T>
.- If there are cycles, define a "direction" and use
std::shared_ptr<T>
in one direction andstd::weak_ptr<T>
in the other.If the object owns you, but there is potential of having no owner, use normal pointers
T*
(e.g. parent pointers).If the object owns you (or otherwise has guaranteed existence), use references
T&
.Caveat: Be aware of the costs of smart pointers. In memory or performance limited environments, it could be beneficial to just use normal pointers with a more manual scheme for managing memory.
The costs:
std::shared_ptr
has the overhead of a reference count increment on copy, plus a decrement on destruction followed by a 0-count check with deletion of the held object. Depending on the implementation, this can bloat your code and cause performance issues.Examples:
A binary tree does not own its parent, but the existence of a tree implies the existence of its parent (or
nullptr
for root), so that uses a normal pointer. A binary tree (with value semantics) has sole ownership of its children, so those arestd::unique_ptr
.Here, the list node owns its next and previous lists, so we define a direction and use
shared_ptr
for next andweak_ptr
for prev to break the cycle.Use
unique_ptr<T>
all the time except when you need reference counting, in which case useshared_ptr<T>
(and for very rare cases,weak_ptr<T>
to prevent reference cycles). In almost every case, transferrable unique ownership is just fine.Raw pointers: Good only if you need covariant returns, non-owning pointing which can happen. They're not terrifically useful otherwise.
Array pointers:
unique_ptr
has a specialization forT[]
which automatically callsdelete[]
on the result, so you can safely dounique_ptr<int[]> p(new int[42]);
for example.shared_ptr
you'd still need a custom deleter, but you wouldn't need a specialized shared or unique array pointer. Of course, such things are usually best replaced bystd::vector
anyway. Unfortunatelyshared_ptr
does not provide an array access function, so you'd still have to manually callget()
, butunique_ptr<T[]>
providesoperator[]
instead ofoperator*
andoperator->
. In any case, you have to bounds check yourself. This makesshared_ptr
slightly less user-friendly, although arguably the generic advantage and no Boost dependency makesunique_ptr
andshared_ptr
the winners again.Scoped pointers: Made irrelevant by
unique_ptr
, just likeauto_ptr
.There's really nothing more to it. In C++03 without move semantics this situation was very complicated, but in C++11 the advice is very simple.
There are still uses for other smart pointers, like
intrusive_ptr
orinterprocess_ptr
. However, they're very niche and completely unnecessary in the general case.