Introduction
Synopsis
Members
Free Functions
Example
Handle/Body Idiom
Frequently Asked Questions
Smart Pointer Timings
The shared_ptr class template stores a pointer to a dynamically allocated object. (Dynamically allocated objects are allocated with the C++ new expression.) The object pointed to is guaranteed to be deleted when the last shared_ptr pointing to it is destroyed or reset. See the example.
Every shared_ptr meets the CopyConstructible and Assignable requirements of the C++ Standard Library, and so can be used in standard library containers. Comparison operators are supplied so that shared_ptr works with the standard library's associative containers.
Normally, a shared_ptr cannot correctly hold a pointer to a dynamically allocated array. See shared_array for that usage.
Because the implementation uses reference counting, shared_ptr will not work correctly with cyclic data structures. For example, if main() holds a shared_ptr to A, which directly or indirectly holds a shared_ptr back to A, A's use count will be 2. Destruction of the original shared_ptr will leave A dangling with a use count of 1. Use weak_ptr to "break cycles."
The class template is parameterized on T, the type of the object pointed to. shared_ptr and most of its member functions place no requirements on T; it is allowed to be an incomplete type, or void. Member functions that do place additional requirements (constructors, reset) are explicitly documented below.
shared_ptr<T> can be implicitly converted to shared_ptr<U> whenever T* can be implicitly converted to U*. In particular, shared_ptr<T> is implicitly convertible to shared_ptr<T const>, to shared_ptr<U> where U is an accessible base of T, and to shared_ptr<void>.
namespace boost { class use_count_is_zero: public std::exception; template<typename T> class weak_ptr; template<typename T> class shared_ptr { public: typedef T element_type; shared_ptr (); template<typename Y> explicit shared_ptr (Y * p); template<typename Y, typename D> shared_ptr(Y * p, D d); ~shared_ptr(); // never throws shared_ptr(shared_ptr const & r); // never throws template<typename Y> shared_ptr(shared_ptr<Y> const & r); // never throws explicit shared_ptr(weak_ptr const & r); template<typename Y> shared_ptr(std::auto_ptr<Y> & r); shared_ptr & operator=(shared_ptr const & r); // never throws template<typename Y> shared_ptr & operator=(shared_ptr<Y> const & r); // never throws template<typename Y> shared_ptr & operator=(std::auto_ptr<Y> & r); void reset (); template<typename Y> void reset (Y * p); template<typename Y> template<typename D> void reset(Y * p, D d); T & operator*() const; // never throws T * operator->() const; // never throws T * get() const; // never throws bool unique() const; // never throws long use_count() const; // never throws operator implementation-defined-type () const; // never throws void swap(shared_ptr<T> & b); // never throws }; template<typename T, typename U> bool operator==(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws template<typename T, typename U> bool operator!=(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws template<typename T> bool operator<(shared_ptr<T> const & a, shared_ptr<T> const & b); // never throws template<typename T> void swap(shared_ptr<T> & a, shared_ptr<T> & b); // never throws template<typename T, typename U> shared_ptr<T> shared_static_cast(shared_ptr<U> const & r); // never throws template<typename T, typename U> shared_ptr<T> shared_dynamic_cast(shared_ptr<U> const & r); template<typename T, typename U> shared_ptr<T> shared_polymorphic_cast(shared_ptr<U> const & r); template<typename T, typename U> shared_ptr<T> shared_polymorphic_downcast(shared_ptr<U> const & r); // never throws }
typedef T element_type;
Provides the type of the template parameter T.
shared_ptr();
Effects: Constructs a shared_ptr.
Postconditions: use count is 1; the stored pointer is 0.
Throws: std::bad_alloc.
Exception safety: If an exception is thrown, the constructor has no effect.
template<typename Y> explicit shared_ptr(Y * p);
Requirements: p must be convertible to T *. Y must be a complete type. The expression
delete p
must be well-formed, must not invoke undefined behavior, and must not throw exceptions.Effects: Constructs a shared_ptr, storing a copy of p.
Postconditions: use count is 1.
Throws: std::bad_alloc.
Exception safety: If an exception is thrown,
delete p
is called.Notes: p must be a pointer to an object that was allocated via a C++ new expression or be 0. The postcondition that use count is 1 holds even if p is 0; invoking delete on a pointer that has a value of 0 is harmless.
template<typename Y, typename D> shared_ptr(Y * p, D d);
Requirements: p must be convertible to T *. The copy constructor and destructor of D must not throw. The expression
d(p)
must be well-formed, must not invoke undefined behavior, and must not throw exceptions.Effects: Constructs a shared_ptr, storing a copy of p and d.
Postconditions: use count is 1.
Throws: std::bad_alloc.
Exception safety: If an exception is thrown,
d(p)
is called.Notes: When the the time comes to delete the object pointed to by p,
d(p)
is invoked.
shared_ptr(shared_ptr const & r); // never throws template<typename Y> shared_ptr(shared_ptr<Y> const & r); // never throws
Effects: Constructs a shared_ptr, as if by storing a copy of the pointer stored in r.
Postconditions: use count for all copies is increased by one.
Throws: nothing.
explicit shared_ptr(weak_ptr const & r);
Effects: Constructs a shared_ptr, as if by storing a copy of the pointer stored in r.
Postconditions: use count for all copies is increased by one.
Throws: use_count_is_zero when
r.use_count() == 0
.Exception safety: If an exception is thrown, the constructor has no effect.
template<typename Y> shared_ptr(std::auto_ptr<Y> & r);
Effects: Constructs a shared_ptr, as if by storing a copy of r.release().
Postconditions: use count for all copies is increased by one.
Throws: std::bad_alloc.
Exception safety: If an exception is thrown, the constructor has no effect.
~shared_ptr(); // never throws
Effects: If *this is the sole owner (
use_count() == 1
), destroys the object pointed to by the stored pointer.Postconditions: use count for all remaining copies is decreased by one.
Throws: nothing.
shared_ptr & operator=(shared_ptr const & r); // never throws template<typename Y> shared_ptr & operator=(shared_ptr<Y> const & r); // never throws template<typename Y> shared_ptr & operator=(std::auto_ptr<Y> & r);
Effects: Equivalent to
shared_ptr(r).swap(*this)
.Notes: The implementation is free to meet the effects (and the implied guarantees) via different means, without creating a temporary. In particular, in the example:
shared_ptr<int> p(new int); shared_ptr<void> q(p); p = p; q = p;both assignments may be no-ops.
void reset();
Effects: Equivalent to
shared_ptr().swap(*this)
.
template<typename Y> void reset(Y * p);
Effects: Equivalent to
shared_ptr(p).swap(*this)
.
template<typename Y, typename D> void reset(Y * p, D d);
Effects: Equivalent to
shared_ptr(p, d).swap(*this)
.
T & operator*() const; // never throws
Requirements: The stored pointer must not be 0.
Returns: a reference to the object pointed to by the stored pointer.
Throws: nothing.
T * operator->() const; // never throws
Requirements: The stored pointer must not be 0.
Returns: the stored pointer.
Throws: nothing.
T * get() const; // never throws
Returns: the stored pointer.
Throws: nothing.
bool unique() const; // never throws
Returns:
use_count() == 1
.Throws: nothing.
Notes:
unique()
may be faster thanuse_count()
.
long use_count() const; // never throws
Returns: the number of shared_ptr objects sharing ownership of the stored pointer.
Throws: nothing.
Notes:
use_count()
is not necessarily efficient. Use only for debugging and testing purposes, not for production code.
operator implementation-defined-type () const; // never throws
Returns: an implementation defined value that, when used in boolean contexts, is equivalent to
get() != 0
.Throws: nothing.
Notes: This conversion operator allows shared_ptr objects to be used in boolean contexts, like
if (p && p->valid()) {}
. The actual target type is typically a pointer to a member function, avloiding many of the implicit conversion pitfalls.
void swap(shared_ptr & b); // never throws
Effects: Exchanges the contents of the two smart pointers.
Throws: nothing.
template<typename T, typename U> bool operator==(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws
Returns:
a.get() == b.get()
.Throws: nothing.
template<typename T, typename U> bool operator!=(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws
Returns:
a.get() != b.get()
.Throws: nothing.
template<typename T> bool operator<(shared_ptr<T> const & a, shared_ptr<T> const & b); // never throws
Returns: an implementation-defined value such that operator< is a strict weak ordering as described in section 25.3
[lib.alg.sorting]
of the C++ standard.Throws: nothing.
Notes: Allows shared_ptr objects to be used as keys in associative containers.
template<typename T> void swap(shared_ptr<T> & a, shared_ptr<T> & b) // never throws
Effects: Equivalent to
a.swap(b)
.Throws: nothing.
Notes: Matches the interface of std::swap. Provided as an aid to generic programming.
template<typename T, typename U> shared_ptr<T> shared_static_cast(shared_ptr<U> const & r); // never throws
Requires: The expression
static_cast<T*>(r.get())
must be well-formed.Returns: A shared_ptr<T> object that stores a copy of
static_cast<T*>(r.get())
and shares ownership with r.Throws: nothing.
Notes: the seemingly equivalent expression
shared_ptr<T>(static_cast<T*>(r.get()))
will eventually result in undefined behavior, attempting to delete the same object twice.
template<typename T, typename U> shared_ptr<T> shared_dynamic_cast(shared_ptr<U> const & r);
Requires: The expression
dynamic_cast<T*>(r.get())
must be well-formed and its behavior defined.Returns:
- When
dynamic_cast<T*>(r.get())
returns a nonzero value, a shared_ptr<T> object that stores a copy of it and shares ownership with r;- Otherwise, a default-constructed shared_ptr<T> object.
Throws: std::bad_alloc.
Exception safety: If an exception is thrown, the function has no effect.
Notes: the seemingly equivalent expression
shared_ptr<T>(dynamic_cast<T*>(r.get()))
will eventually result in undefined behavior, attempting to delete the same object twice.
template<typename T, typename U> shared_ptr<T> shared_polymorphic_cast(shared_ptr<U> const & r);
Requires: The expression
polymorphic_cast<T*>(r.get())
must be well-formed and its behavior defined.Returns: A shared_ptr<T> object that stores a copy of
polymorphic_cast<T*>(r.get())
and shares ownership with r.Throws: std::bad_cast when the pointer cannot be converted.
Exception safety: If an exception is thrown, the function has no effect.
template<typename T, typename U> shared_ptr<T> shared_polymorphic_downcast(shared_ptr<U> const & r); // never throws
Requires: The expression
polymorphic_downcast<T*>(r.get())
must be well-formed and its behavior defined.Returns: A shared_ptr<T> object that stores a copy of
polymorphic_downcast<T*>(r.get())
and shares ownership with r.Throws: nothing.
See shared_ptr_example.cpp for a complete example program. The program builds a std::vector and std::set of shared_ptr objects.
Note that after the containers have been populated, some of the shared_ptr objects will have a use count of 1 rather than a use count of 2, since the set is a std::set rather than a std::multiset, and thus does not contain duplicate entries. Furthermore, the use count may be even higher at various times while push_back and insert container operations are performed. More complicated yet, the container operations may throw exceptions under a variety of circumstances. Getting the memory management and exception handling in this example right without a smart pointer would be a nightmare.
One common usage of shared_ptr is to implement a handle/body (also called pimpl) idiom which avoids exposing the body (implementation) in the header file.
The shared_ptr_example2_test.cpp sample program includes a header file, shared_ptr_example2.hpp, which uses a shared_ptr<> to an incomplete type to hide the implementation. The instantiation of member functions which require a complete type occurs in the shared_ptr_example2.cpp implementation file. Note that there is no need for an explicit destructor. Unlike ~scoped_ptr, ~shared_ptr does not require that T be a complete type.
Q. There are several variations of shared pointers, with different
tradeoffs; why does the smart pointer library supply only a single
implementation? It would be useful to be able to experiment with each type so
as to find the most suitable for the job at hand?
A. An important goal of shared_ptr is to provide a
standard shared-ownership pointer. Having a single pointer type is important
for stable library interfaces, since different shared pointers typically cannot
interoperate, i.e. a reference counted pointer (used by library A) cannot share
ownership with a linked pointer (used by library B.)
Q. Why doesn't shared_ptr have template parameters supplying
traits or policies to allow extensive user customization?
A. Parameterization discourages users. The shared_ptr template is
carefully crafted to meet common needs without extensive parameterization. Some
day a highly configurable smart pointer may be invented that is also very easy
to use and very hard to misuse. Until then, shared_ptr is the smart
pointer of choice for a wide range of applications. (Those interested in policy
based smart pointers should read
Modern C++ Design by Andrei Alexandrescu.)
Q. I am not convinced. Default parameters can be used where appropriate to
hide the complexity. Again, why not policies?
A. Template parameters affect the type. See the answer to the first
question above.
Q. Why doesn't shared_ptr use a linked list implementation?
A. A linked list implementation does not offer enough advantages to
offset the added cost of an extra pointer. See timings
page. In addition, it is expensive to make a linked list implementation thread
safe.
Q. Why doesn't shared_ptr (or any of the other Boost smart
pointers) supply an automatic conversion to T*?
A. Automatic conversion is believed to be too error prone.
Q. Why does shared_ptr supply use_count()?
A. As an aid to writing test cases and debugging displays. One of the
progenitors had use_count(), and it was useful in tracking down bugs in a
complex project that turned out to have cyclic-dependencies.
Q. Why doesn't shared_ptr specify complexity requirements?
A. Because complexity requirements limit implementors and complicate the
specification without apparent benefit to shared_ptr users. For example,
error-checking implementations might become non-conforming if they had to meet
stringent complexity requirements.
Q. Why doesn't shared_ptr provide a release() function?
A. shared_ptr cannot give away ownership unless it's unique()
because the other copy will still destroy the object.
Consider:
shared_ptr<int> a(new int); shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2 int * p = a.release(); // Who owns p now? b will still call delete on it in its destructor.
Q. Why doesn't shared_ptr provide (your pet feature here)?
A. Because (your pet feature here) would mandate a reference counted
implementation or a linked list implementation, or some other specific
implementation. This is not the intent.
Revised 04 May 2002
Copyright 1999 Greg Colvin and Beman Dawes. Copyright 2002 Darin Adler. Copyright 2002 Peter Dimov. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.