c++boost.gif (8819 bytes)shared_ptr class template

Introduction
Best Practices
Synopsis
Members
Free Functions
Example
Handle/Body Idiom
Thread Safety
Frequently Asked Questions
Smart Pointer Timings

Introduction

The shared_ptr class template stores a pointer to a dynamically allocated object, typically with a 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, cycles of shared_ptr instances will not be reclaimed. 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>.

Best Practices

A simple guideline that nearly eliminates the possibility of memory leaks is: always use a named smart pointer variable to hold the result of new. Every occurence of the new keyword in the code should have the form:

shared_ptr<T> p(new Y);

It is, of course, acceptable to use another smart pointer in place of shared_ptr above; having T and Y be the same type, or passing arguments to Y's constructor is also OK.

If you observe this guideline, it naturally follows that you will have no explicit deletes; try/catch constructs will be rare.

Avoid using unnamed shared_ptr temporaries to save typing; to see why this is dangerous, consider this example:

void f(shared_ptr<int>, int);
int g();

void ok()
{
    shared_ptr<int> p(new int(2));
    f(p, g());
}

void bad()
{
    f(shared_ptr<int>(new int(2)), g());
}

The function ok follows the guideline to the letter, whereas bad constructs the temporary shared_ptr in place, admitting the possibility of a memory leak. Since function arguments are evaluated in unspecified order, it is possible for new int(2) to be evaluated first, g() second, and we may never get to the shared_ptr constructor if g throws an exception. See Herb Sutter's treatment of the issue for more information.

Synopsis

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
      template<typename Y> explicit shared_ptr(weak_ptr<Y> const & r);
      template<typename Y> explicit 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, 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 unspecified-bool-type() const; // never throws

      void swap(shared_ptr & 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> T * get_pointer(shared_ptr<T> const & p); // 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

}

[It might be convenient to relax the requirements on shared_ptr's signature, allowing an additional, defaulted, template parameter; the parameter can encode the threading model, for example. This would help in detecting possible ODR violations.

On the other hand, using shared_ptr as an argument to a template template parameter requires an exact signature match. Metaprogramming experts tend to deemphasize template template parameters as they are too inflexible, but the alternative is typically an std::allocator::rebind-type "hack".]

Members

element_type

typedef T element_type;

Provides the type of the template parameter T.

constructors

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.

[The poscondition of use_count() == 1 is too strong. Having the nothrow guarantee is important, since reset() is specified in terms of the default constructor, but the current specification requires that a count be allocated. Therefore, this postcondition will be dropped in a future release. The use count of a default-constructed shared_ptr, including all copies created from it, will probably be left unspecified.

There are two possible nothrow implementations, one stores 0 as a pointer to the reference count, the other uses a single statically allocated count for all default-constructed shared_ptrs. The second option is difficult to achieve in the current header-only reference implementation due to thread safety issues and initialization order, but it should not be precluded by the specification.

A future release may enable shared_ptr construction from a literal zero, for consistency with built-in pointers. It is not clear yet whether this constructor should be left implicit, enabling 0 to be used as a shorthand for shared_ptr<T>().]

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.

[This constructor has been changed to a template in order to remember the actual pointer type passed. The destructor will call delete with the same pointer, complete with its original type, even when T does not have a virtual destructor, or is void.

In the current implementation, if p is convertible to counted_base *, shared_ptr will use the embedded reference count supplied by counted_base. This is an (experimental) attempt to provide a way for shared_ptr to be constructed from a raw pointer such as this. A free function shared_from_this(q) performs the conversion when q is convertible to counted_base const *.

The optional intrusive counting employed by the current implementation allows shared_ptr to interoperate with intrusive_ptr, an experimental generic intrusive-counted smart pointer.

Another possible implementation is to use a global pointer-to-count map instead of intrusive counting. shared_from_this would no longer be O(1), which is a concern for some users, although I do not expect any performance problems, since the operation is rare. Maintaining a global map is difficult; it needs to be initialized before any shared_ptr instances are constructed, and the initialization needs to be thread safe. In addition, under the Windows dynamic library model, it is possible for several maps to exist.

It is not yet clear which implementation should be used, or whether the specification should allow both; nevertheless, the ability to make a shared_ptr from this is considered essential by experienced smart pointer users.]

template<typename Y, typename D> shared_ptr(Y * p, D d);

Requirements: p must be convertible to T *. D must be CopyConstructible. 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, the stored copy of d is invoked with the stored copy of p as an argument.

[Custom deallocators allow a factory function returning a shared_ptr to insulate the user from its memory allocation strategy. Since the deallocator is not part of the type, changing the allocation strategy does not break source or binary compatibility, and does not require a client recompilation. For example, a "no-op" deallocator is useful when returning a shared_ptr to a statically allocated object.

The support for custom deallocators does not impose significant overhead. Other shared_ptr features still require a deallocator to be kept.

The requirement that the copy constructor of D does not throw comes from the pass by value. If the copy constructor throws, the pointer is leaked. Removing the requirement requires a pass by (const) reference. The problems are that (1) pass by value conveniently changes functions (function references) to function pointers (this has to be performed manually otherwise and some compilers may not be able to do it) and (2) const references don't currently (per the standard) bind to functions. This can be solved (I think) but it requires an overload set that breaks on many compilers due to 14.5.5.2 problems (and of course it will break on compilers that don't do partial ordering at all.)

The requrement will be removed when the aforementioned issues are resolved.]

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.

[The postcondition will be relaxed when a default-constructed shared_ptr is being copied.]

template<typename Y> explicit shared_ptr(weak_ptr<Y> 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.

[This constructor is an optional part of the specification; it depends on the existence of weak_ptr. It is true that weak_ptr support imposes overhead on every shared_ptr user, regardless of whether weak pointers are used.

On the other hand, cyclic references are a serious problem with all reference counted designs. Not providing a solution within the library is unacceptable; if users are forced to reinvent the weak pointer wheel, there is substantial probability that they will get it wrong, as designing a safe weak_ptr interface is non-trivial.

My opinion is that the added functionality is worth the cost. weak_ptr is provided in the reference implementation as a proof of concept.]

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 is 1.

Throws: std::bad_alloc.

Exception safety: If an exception is thrown, the constructor has no effect.

[This constructor takes a the source auto_ptr by reference and not by value, and cannot accept auto_ptr temporaries. This is by design, as the constructor offers the strong guarantee.]

destructor

~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.

assignment

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 use count updates caused by the temporary object construction and destruction are not considered observable side effects, and 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.

[Some experts consider the note to be redundant, as it appears to essentially mirror the "as if" rile. However, experience suggests that when C++ code is used to describe effects, it is often misinterpreted as required implementation. In addition, it is not entirely clear whether the "as if" rule actually applies here, so it's better to be explicit about the possible optimizations.]

reset

void reset();

Effects: Equivalent to shared_ptr().swap(*this).

[reset() will offer the nothrow guarantee in a future implementation.]

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).

indirection

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.

get

T * get() const; // never throws

Returns: the stored pointer.

Throws: nothing.

unique

bool unique() const; // never throws

Returns: use_count() == 1.

Throws: nothing.

Notes: unique() may be faster than use_count(). If you are using unique() to implement copy on write, do not rely on a specific value when the stored pointer is zero.

[In a future release, unique() will return an unspecified value for a default-constructed shared_ptr.]

use_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.

conversions

operator unspecified-bool-type () const; // never throws

Returns: an unspecified 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, avoiding many of the implicit conversion pitfalls.

[The conversion to bool is not merely syntactic sugar. It allows shared_ptrs to be declared in conditions when using shared_dynamic_cast or make_shared.]

swap

void swap(shared_ptr & b); // never throws

Effects: Exchanges the contents of the two smart pointers.

Throws: nothing.

Free Functions

comparison

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 unspecified 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.

[Operator< has been preferred over a std::less specialization for consistency and legality reasons, as std::less is required to return the results of operator<, and many standard algorithms use operator< instead of std::less for comparisons when a predicate is not supplied. Composite objects, like std::pair, also implement their operator< in terms of their contained subobjects' operator<.

The rest of the comparison operators are omitted by design.]

swap

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.

[swap is defined in the same namespace as shared_ptr as this is currently the only legal way to supply a swap function that has a chance to be used by the standard library.]

get_pointer

template<typename T>
  T * get_pointer(shared_ptr<T> const & p); // never throws

Returns: p.get().

Throws: nothing.

Notes: Provided as an aid to generic programming. Used by mem_fn.

shared_static_cast

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.

shared_dynamic_cast

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:

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.

shared_polymorphic_cast

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.

shared_polymorphic_downcast

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.

Example

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.

Handle/Body Idiom

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.

Thread Safety

shared_ptr objects offer the same level of thread safety as built-in types. A shared_ptr instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

Any other simultaneous accesses result in undefined behavior.

Examples:

shared_ptr<int> p(new int(42));

//--- Example 1 ---

// thread A
shared_ptr<int> p2(p); // reads p

// thread B
shared_ptr<int> p3(p); // OK, multiple reads are safe

//--- Example 2 ---

// thread A

p.reset(new int(1912)); // writes p

// thread B
p2.reset(); // OK, writes p2

//--- Example 3 ---

// thread A
p = p3; // reads p3, writes p

// thread B
p3.reset(); // writes p3; undefined, simultaneous read/write

//--- Example 4 ---

// thread A
p3 = p2; // reads p2, writes p3

// thread B
// p2 goes out of scope: undefined, the destructor is considered a "write access"

//--- Example 5 ---

// thread A
p3.reset(new int(1));

// thread B
p3.reset(new int(2)); // undefined, multiple writes

shared_ptr uses Boost.Config to detect whether the implementation supports threads. If your program is single-threaded, but your platform is autodetected by Boost.Config as supporting multiple threads, #define BOOST_DISABLE_THREADS to eliminate the thread safety overhead.

Frequently Asked Questions

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 $Date: 2002/09/23 13:32:54 $

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.