From 1742c37942455c617cf74dd48e41621ef3f2594e Mon Sep 17 00:00:00 2001 From: Frank Mori Hess Date: Wed, 11 Mar 2009 15:08:14 +0000 Subject: [PATCH] Merged [51699] and [51700] from trunk to release. Closes #1897 [SVN r51703] --- make_shared.html | 119 ++++++++++++++++++ shared_ptr.htm | 309 ++++++++++++++++++++++++----------------------- smart_ptr.htm | 159 ++++++++++++------------ 3 files changed, 361 insertions(+), 226 deletions(-) create mode 100644 make_shared.html diff --git a/make_shared.html b/make_shared.html new file mode 100644 index 0000000..e47fe2a --- /dev/null +++ b/make_shared.html @@ -0,0 +1,119 @@ + + + + make_shared and allocate_shared + + + +

boost.png (6897 bytes)make_shared and allocate_shared function templates

+

Introduction
+ Synopsis
+ Free Functions
+ Example
+

Introduction

+

Consistent use of shared_ptr + can eliminate the need to use an explicit delete, + but alone it provides no support in avoiding explicit new. + There have been repeated requests from users for a factory function that creates + an object of a given type and returns a shared_ptr to it. + Besides convenience and style, such a function is also exception safe and + considerably faster because it can use a single allocation for both the object + and its corresponding control block, eliminating a significant portion of + shared_ptr's construction overhead. + This eliminates one of the major efficiency complaints about shared_ptr. +

+

The header file <boost/make_shared.hpp> provides a family of overloaded function templates, + make_shared and allocate_shared, to address this need. + make_shared uses the global operator new to allocate memory, + whereas allocate_shared uses an user-supplied allocator, allowing finer control.

+

+ The rationale for choosing the name make_shared is that the expression + make_shared<Widget>() can be read aloud and conveys the intended meaning.

+

Synopsis

+
namespace boost {
+
+  template<typename T> class shared_ptr;
+
+  template<typename T>
+    shared_ptr<T> make_shared();
+
+  template<typename T, typename A>
+    shared_ptr<T> allocate_shared( A const & );
+
+#if defined( BOOST_HAS_VARIADIC_TMPL ) && defined( BOOST_HAS_RVALUE_REFS )	// C++0x prototypes
+
+  template<typename T, typename... Args>
+    shared_ptr<T> make_shared( Args && ... args );
+
+  template<typename T, typename A, typename... Args>
+    shared_ptr<T> allocate_shared( A const & a, Args && ... args );
+
+#else // no C++0X support
+
+  template<typename T, typename Arg1 >
+    shared_ptr<T> make_shared( Arg1 const & arg1 );
+  template<typename T, typename Arg1, typename Arg2 >
+    shared_ptr<T> make_shared( Arg1 const & arg1, Arg2 const & arg2 );
+// ...
+  template<typename T, typename Arg1, typename Arg2, ..., typename ArgN >
+    shared_ptr<T> make_shared( Arg1 const & arg1, Arg2 const & arg2, ..., ArgN const & argN );
+
+  template<typename T, typename A, typename Arg1 >
+    shared_ptr<T> allocate_shared( A const & a, Arg1 const & arg1 );
+  template<typename T, typename A, typename Arg1, typename Arg2 >
+    shared_ptr<T> allocate_shared( Arg1 const & arg1, Arg2 const & arg2 );
+// ...
+  template<typename T, typename A, typename Arg1, typename Arg2, ..., typename ArgN >
+    shared_ptr<T> allocate_shared( A const & a, Arg1 const & arg1, Arg2 const & arg2, ..., ArgN const & argN );
+
+#endif
+}
+

Free Functions

+
template<class T, class... Args>
+    shared_ptr<T> make_shared( Args && ... args );
+template<class T, class A, class... Args>
+    shared_ptr<T> allocate_shared( A const & a, Args && ... args );
+
+

Requires: The expression new( pv ) T( std::forward<Args>(args)... ), + where pv is a void* pointing to storage suitable + to hold an object of type T, + shall be well-formed. A shall be an Allocator, + as described in section 20.1.5 (Allocator requirements) of the C++ Standard. + The copy constructor and destructor of A shall not throw.

+

Effects: Allocates memory suitable for an object of type T + and constructs an object in it via the placement new expression new( pv ) T() + or new( pv ) T( std::forward<Args>(args)... ). + allocate_shared uses a copy of a to allocate memory. + If an exception is thrown, has no effect.

+

Returns: A shared_ptr instance that stores and owns the address + of the newly constructed object of type T.

+

Postconditions: get() != 0 && use_count() == 1.

+

Throws: bad_alloc, or an exception thrown from A::allocate + or the constructor of T.

+

Notes: This implementation allocates the memory required for the + returned shared_ptr and an object of type T in a single + allocation. This provides efficiency equivalent to an intrusive smart pointer.

+

The prototypes shown above are used if your compiler supports rvalue references + and variadic templates. They perfectly forward the args parameters to + the constructors of T.

+

Otherwise, the implementation will fall back on + forwarding the arguments to the constructors of T as const references. + If you need to pass a non-const reference to a constructor of T, + you may do so by wrapping the parameter in a call to boost::ref. + In addition, you will be + limited to a maximum of 9 arguments (not counting the allocator argument of + allocate_shared).

+
+

Example

+
boost::shared_ptr<std::string> x = boost::make_shared<std::string>("hello, world!");
+std::cout << *x;
+
+

+ $Date: 2008-05-19 15:42:39 -0400 (Mon, 19 May 2008) $

+

Copyright 2008 Peter Dimov. Copyright 2008 Frank Mori Hess. + Distributed under the Boost Software License, + Version 1.0. See accompanying file LICENSE_1_0.txt + or copy at http://www.boost.org/LICENSE_1_0.txt.

+ + diff --git a/shared_ptr.htm b/shared_ptr.htm index 5b4444f..77e1fa8 100644 --- a/shared_ptr.htm +++ b/shared_ptr.htm @@ -19,54 +19,54 @@ Smart Pointer Timings
Programming Techniques

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 +

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 +

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 +

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 +

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 + 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 +

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

-

shared_ptr is now part of TR1, the first C++ - Library Technical Report. The latest draft of TR1 is available +

shared_ptr is now part of TR1, the first C++ + Library Technical Report. The latest draft of TR1 is available at the following location:

http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1745.pdf (1.36Mb PDF)

-

This implementation conforms to the TR1 specification, with the only exception +

This implementation conforms to the TR1 specification, with the only exception that it resides in namespace boost instead of std::tr1.

Best Practices

-

A simple guideline that nearly eliminates the possibility of memory leaks is: +

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 + 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 + 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 +

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 +

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();
@@ -83,13 +83,18 @@ void bad()
 }
 

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 + 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. + shared_ptr constructor if g throws an exception. See Herb Sutter's treatment (also here) of the issue for more information.

+

The exception safety problem described above may also be eliminated by using + the make_shared + or allocate_shared + factory functions defined in boost/make_shared.hpp. These factory functions also provide + an efficiency benefit by consolidating allocations.

Synopsis

namespace boost {
 
@@ -115,7 +120,7 @@ void bad()
       template<class Y> explicit shared_ptr(weak_ptr<Y> const & r);
       template<class Y> explicit shared_ptr(std::auto_ptr<Y> & r);
 
-      shared_ptr & operator=(shared_ptr const & r); // never throws  
+      shared_ptr & operator=(shared_ptr const & r); // never throws
       template<class Y> shared_ptr & operator=(shared_ptr<Y> const & r); // never throws
       template<class Y> shared_ptr & operator=(std::auto_ptr<Y> & r);
 
@@ -178,32 +183,32 @@ void bad()
 			

Postconditions: use_count() == 0 && get() == 0.

Throws: nothing.

-

[The nothrow guarantee is important, since reset() is specified - in terms of the default constructor; this implies that the constructor must not +

[The nothrow guarantee is important, since reset() is specified + in terms of the default constructor; this implies that the constructor must not allocate memory.]

template<class 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 + 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 that owns the pointer p.

Postconditions: use_count() == 1 && get() == p.

-

Throws: std::bad_alloc, or an implementation-defined +

Throws: std::bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.

-

Exception safety: If an exception is thrown, delete p is +

Exception safety: If an exception is thrown, delete p is called.

-

Notes: p must be a pointer to an object that was +

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 +

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

-

The optional intrusive counting support has been dropped as it exposes too much - implementation details and doesn't interact well with weak_ptr. +

The optional intrusive counting support has been dropped as it exposes too much + implementation details and doesn't interact well with weak_ptr. The current implementation uses a different mechanism, enable_shared_from_this, to solve the "shared_ptr from this" problem.]

@@ -212,46 +217,46 @@ void bad() template<class Y, class D, class A> shared_ptr(Y * p, D d, A a);

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 + 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. - A must be an Allocator, as described in section 20.1.5 (Allocator + A must be an Allocator, as described in section 20.1.5 (Allocator requirements) of the C++ Standard.

Effects: Constructs a shared_ptr that owns the pointer - p and the deleter d. The second constructor allocates + p and the deleter d. The second constructor allocates memory using a copy of a.

Postconditions: use_count() == 1 && get() == p.

-

Throws: std::bad_alloc, or an implementation-defined +

Throws: std::bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.

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, +

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 + 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, and other variations allow a shared_ptr to be used as a wrapper for another smart pointer, easing interoperability.

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

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 main problem with pass by reference lies in its interaction with rvalues. A - const reference may still cause a copy, and will require a const operator(). A - non-const reference won't bind to an rvalue at all. A good solution to this +

The main problem with pass by reference lies in its interaction with rvalues. A + const reference may still cause a copy, and will require a const operator(). A + non-const reference won't bind to an rvalue at all. A good solution to this problem is the rvalue reference proposed in N1377/N1385.]

shared_ptr(shared_ptr const & r); // never throws
 template<class Y> shared_ptr(shared_ptr<Y> const & r); // never throws
-

Effects: If r is empty, constructs an empty shared_ptr; +

Effects: If r is empty, constructs an empty shared_ptr; otherwise, constructs a shared_ptr that shares ownership with r.

-

Postconditions: get() == r.get() && use_count() == +

Postconditions: get() == r.get() && use_count() == r.use_count().

Throws: nothing.

@@ -268,21 +273,21 @@ template<class Y> shared_ptr(shared_ptr<Y> const & r); // never r and stores a copy of the pointer stored in r.

Postconditions: use_count() == r.use_count().

Throws: bad_weak_ptr when r.use_count() == 0.

-

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

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

template<class 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() == 1.

-

Throws: std::bad_alloc, or an implementation-defined +

Throws: std::bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.

-

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

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; an rvalue reference +

[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; an rvalue reference would solve this problem, too.]

destructor

~shared_ptr(); // never throws
@@ -290,15 +295,15 @@ template<class Y> shared_ptr(shared_ptr<Y> const & r); // never

Effects:

  • - If *this is empty, or shares ownership with - another shared_ptr instance (use_count() > 1), + If *this is empty, or shares ownership with + another shared_ptr instance (use_count() > 1), there are no side effects.
  • - Otherwise, if *this owns a pointer p + Otherwise, if *this owns a pointer p and a deleter d, d(p) is called.
  • - Otherwise, *this owns a pointer p, + Otherwise, *this owns a pointer p, and delete p is called.

Throws: nothing.

@@ -309,9 +314,9 @@ template<class Y> shared_ptr & operator=(std::auto_ptr<Y> &

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

Returns: *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 +

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);
@@ -365,32 +370,32 @@ q = p;
 		

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 +

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.

use_count

long use_count() const; // never throws
-

Returns: the number of shared_ptr objects, *this included, +

Returns: the number of shared_ptr objects, *this included, that share ownership with *this, or 0 when *this is empty.

Throws: nothing.

-

Notes: use_count() is not necessarily efficient. Use only +

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 +

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 +

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 +

[The conversion to bool is not merely syntactic sugar. It allows shared_ptrs to be declared in conditions when using dynamic_pointer_cast or weak_ptr::lock.]

swap

@@ -422,19 +427,19 @@ q = p; operator< is a strict weak ordering as described in section 25.3 [lib.alg.sorting] of the C++ standard;
  • - under the equivalence relation defined by operator<, !(a - < b) && !(b < a), two shared_ptr instances + under the equivalence relation defined by operator<, !(a + < b) && !(b < a), two shared_ptr instances are equivalent if and only if they share ownership or are both empty.
  • Throws: nothing.

    -

    Notes: Allows shared_ptr objects to be used as keys in +

    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 + 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 + 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

    @@ -443,11 +448,11 @@ q = p;

    Effects: Equivalent to a.swap(b).

    Throws: nothing.

    -

    Notes: Matches the interface of std::swap. Provided as an aid to +

    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 + 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<class T>
    @@ -464,13 +469,13 @@ q = p;
     		

    Requires: The expression static_cast<T*>(r.get()) must be well-formed.

    -

    Returns: If r is empty, an empty shared_ptr<T>; +

    Returns: If r is empty, an empty shared_ptr<T>; otherwise, 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 +

    will eventually result in undefined behavior, attempting to delete the same object twice.

    const_pointer_cast

    @@ -479,13 +484,13 @@ q = p;

    Requires: The expression const_cast<T*>(r.get()) must be well-formed.

    -

    Returns: If r is empty, an empty shared_ptr<T>; +

    Returns: If r is empty, an empty shared_ptr<T>; otherwise, a shared_ptr<T> object that stores a copy of const_cast<T*>(r.get()) and shares ownership with r.

    Throws: nothing.

    Notes: the seemingly equivalent expression

    shared_ptr<T>(const_cast<T*>(r.get()))

    -

    will eventually result in undefined behavior, attempting to delete the same +

    will eventually result in undefined behavior, attempting to delete the same object twice.

    dynamic_pointer_cast

    @@ -498,14 +503,14 @@ q = p;
    • When dynamic_cast<T*>(r.get()) returns a nonzero value, a - shared_ptr<T> object that stores a copy of it and shares + shared_ptr<T> object that stores a copy of it and shares ownership with r;
    • Otherwise, an empty shared_ptr<T> object.

    Throws: nothing.

    Notes: the seemingly equivalent expression

    shared_ptr<T>(dynamic_cast<T*>(r.get()))

    -

    will eventually result in undefined behavior, attempting to delete the same +

    will eventually result in undefined behavior, attempting to delete the same object twice.

    operator<<

    @@ -520,41 +525,41 @@ q = p; D * get_deleter(shared_ptr<T> const & p);

    Returns: If *this owns a deleter d - of type (cv-unqualified) D, returns &d; + of type (cv-unqualified) D, returns &d; otherwise returns 0.

    Throws: nothing.

    Example

    -

    See shared_ptr_example.cpp for a +

    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 + 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 +

    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 + 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 + 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 +

    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 + 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:

    @@ -601,7 +606,7 @@ p3.reset(new int(1)); p3.reset(new int(2)); // undefined, multiple writes

     

    -

    Starting with Boost release 1.33.0, shared_ptr uses a lock-free +

    Starting with Boost release 1.33.0, shared_ptr uses a lock-free implementation on the following platforms:

    • @@ -614,75 +619,75 @@ p3.reset(new int(2)); // undefined, multiple writes GNU GCC on PowerPC;
    • Windows.
    -

    If your program is single-threaded and does not link to any libraries that might +

    If your program is single-threaded and does not link to any libraries that might have used shared_ptr in its default configuration, you can - #define the macro BOOST_SP_DISABLE_THREADS on a + #define the macro BOOST_SP_DISABLE_THREADS on a project-wide basis to switch to ordinary non-atomic reference count updates.

    -

    (Defining BOOST_SP_DISABLE_THREADS in some, but not all, - translation units is technically a violation of the One Definition Rule and - undefined behavior. Nevertheless, the implementation attempts to do its best to - accommodate the request to use non-atomic updates in those translation units. +

    (Defining BOOST_SP_DISABLE_THREADS in some, but not all, + translation units is technically a violation of the One Definition Rule and + undefined behavior. Nevertheless, the implementation attempts to do its best to + accommodate the request to use non-atomic updates in those translation units. No guarantees, though.)

    -

    You can define the macro BOOST_SP_USE_PTHREADS to turn off the - lock-free platform-specific implementation and fall back to the generic pthread_mutex_t-based +

    You can define the macro BOOST_SP_USE_PTHREADS to turn off the + lock-free platform-specific implementation and fall back to the generic pthread_mutex_t-based code.

    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 +

    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 + 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 +

    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 + 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 +

    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 + 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 + 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 + 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 +

    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 + 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 + 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() + 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);
    @@ -692,25 +697,25 @@ int * p = a.release();
     
     // Who owns p now? b will still call delete on it in its destructor.
    -

    Furthermore, the pointer returned by release() would be difficult - to deallocate reliably, as the source shared_ptr could have been created +

    Furthermore, the pointer returned by release() would be difficult + to deallocate reliably, as the source shared_ptr could have been created with a custom deleter.

    -

    Q. Why is operator->() const, but its return value is a +

    Q. Why is operator->() const, but its return value is a non-const pointer to the element type?

    - A. Shallow copy pointers, including raw pointers, typically don't - propagate constness. It makes little sense for them to do so, as you can always - obtain a non-const pointer from a const one and then proceed to modify the - object through it.shared_ptr is "as close to raw pointers as possible + A. Shallow copy pointers, including raw pointers, typically don't + propagate constness. It makes little sense for them to do so, as you can always + obtain a non-const pointer from a const one and then proceed to modify the + object through it.shared_ptr is "as close to raw pointers as possible but no closer".


    $Date$

    -

    Copyright 1999 Greg Colvin and Beman Dawes. Copyright 2002 Darin Adler. - Copyright 2002-2005 Peter Dimov. Distributed under the Boost Software License, +

    Copyright 1999 Greg Colvin and Beman Dawes. Copyright 2002 Darin Adler. + Copyright 2002-2005 Peter Dimov. Distributed under the Boost Software License, Version 1.0. See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.

    diff --git a/smart_ptr.htm b/smart_ptr.htm index 497c63f..92ad2be 100644 --- a/smart_ptr.htm +++ b/smart_ptr.htm @@ -14,15 +14,15 @@ History and Acknowledgements
    References

    Introduction

    -

    Smart pointers are objects which store pointers to dynamically allocated (heap) - objects. They behave much like built-in C++ pointers except that they - automatically delete the object pointed to at the appropriate time. Smart - pointers are particularly useful in the face of exceptions as they ensure - proper destruction of dynamically allocated objects. They can also be used to +

    Smart pointers are objects which store pointers to dynamically allocated (heap) + objects. They behave much like built-in C++ pointers except that they + automatically delete the object pointed to at the appropriate time. Smart + pointers are particularly useful in the face of exceptions as they ensure + proper destruction of dynamically allocated objects. They can also be used to keep track of dynamically allocated objects shared by multiple owners.

    -

    Conceptually, smart pointers are seen as owning the object pointed to, and thus +

    Conceptually, smart pointers are seen as owning the object pointed to, and thus responsible for deletion of the object when it is no longer needed.

    -

    The smart pointer library provides five smart pointer class templates:

    +

    The smart pointer library provides six smart pointer class templates:

    @@ -38,7 +38,7 @@ - + @@ -58,126 +58,137 @@
    shared_ptr <boost/shared_ptr.hpp>Object ownership shared among multiple pointersObject ownership shared among multiple pointers.
    shared_array

    These templates are designed to complement the std::auto_ptr template.

    -

    They are examples of the "resource acquisition is initialization" idiom - described in Bjarne Stroustrup's "The C++ Programming Language", 3rd edition, +

    They are examples of the "resource acquisition is initialization" idiom + described in Bjarne Stroustrup's "The C++ Programming Language", 3rd edition, Section 14.4, Resource Management.

    -

    A test program, smart_ptr_test.cpp, is +

    Additionally, the smart pointer library provides efficient factory functions + for creating shared_ptr objects:

    +
    + + + + + + +
    make_shared and allocate_shared<boost/make_shared.hpp>Efficient creation of shared_ptr objects.
    +
    +

    A test program, smart_ptr_test.cpp, is provided to verify correct operation.

    -

    A page on compatibility with older versions of - the Boost smart pointer library describes some of the changes since earlier +

    A page on compatibility with older versions of + the Boost smart pointer library describes some of the changes since earlier versions of the smart pointer implementation.

    -

    A page on smart pointer timings will be of interest +

    A page on smart pointer timings will be of interest to those curious about performance issues.

    -

    A page on smart pointer programming techniques lists +

    A page on smart pointer programming techniques lists some advanced applications of shared_ptr and weak_ptr.

    Common Requirements

    -

    These smart pointer class templates have a template parameter, T, which - specifies the type of the object pointed to by the smart pointer. The behavior +

    These smart pointer class templates have a template parameter, T, which + specifies the type of the object pointed to by the smart pointer. The behavior of the smart pointer templates is undefined if the destructor or operator delete for objects of type T throw exceptions.

    -

    T may be an incomplete type at the point of smart pointer declaration. - Unless otherwise specified, it is required that T be a complete type at - points of smart pointer instantiation. Implementations are required to diagnose - (treat as an error) all violations of this requirement, including deletion of +

    T may be an incomplete type at the point of smart pointer declaration. + Unless otherwise specified, it is required that T be a complete type at + points of smart pointer instantiation. Implementations are required to diagnose + (treat as an error) all violations of this requirement, including deletion of an incomplete type. See the description of the checked_delete function template.

    -

    Note that shared_ptr does not have this restriction, as most of +

    Note that shared_ptr does not have this restriction, as most of its member functions do not require T to be a complete type.

    Rationale

    -

    The requirements on T are carefully crafted to maximize safety yet allow - handle-body (also called pimpl) and similar idioms. In these idioms a smart - pointer may appear in translation units where T is an incomplete type. - This separates interface from implementation and hides implementation from - translation units which merely use the interface. Examples described in the - documentation for specific smart pointers illustrate use of smart pointers in +

    The requirements on T are carefully crafted to maximize safety yet allow + handle-body (also called pimpl) and similar idioms. In these idioms a smart + pointer may appear in translation units where T is an incomplete type. + This separates interface from implementation and hides implementation from + translation units which merely use the interface. Examples described in the + documentation for specific smart pointers illustrate use of smart pointers in these idioms.

    -

    Note that scoped_ptr requires that T be a complete type at +

    Note that scoped_ptr requires that T be a complete type at destruction time, but shared_ptr does not.

    Exception Safety

    -

    Several functions in these smart pointer classes are specified as having "no - effect" or "no effect except such-and-such" if an exception is thrown. This - means that when an exception is thrown by an object of one of these classes, - the entire program state remains the same as it was prior to the function call - which resulted in the exception being thrown. This amounts to a guarantee that - there are no detectable side effects. Other functions never throw exceptions. - The only exception ever thrown by functions which do throw (assuming T meets - the common requirements) is std::bad_alloc, - and that is thrown only by functions which are explicitly documented as +

    Several functions in these smart pointer classes are specified as having "no + effect" or "no effect except such-and-such" if an exception is thrown. This + means that when an exception is thrown by an object of one of these classes, + the entire program state remains the same as it was prior to the function call + which resulted in the exception being thrown. This amounts to a guarantee that + there are no detectable side effects. Other functions never throw exceptions. + The only exception ever thrown by functions which do throw (assuming T meets + the common requirements) is std::bad_alloc, + and that is thrown only by functions which are explicitly documented as possibly throwing std::bad_alloc.

    Exception-specifications

    Exception-specifications are not used; see exception-specification rationale.

    -

    All the smart pointer templates contain member functions which can never throw - exceptions, because they neither throw exceptions themselves nor call other +

    All the smart pointer templates contain member functions which can never throw + exceptions, because they neither throw exceptions themselves nor call other functions which may throw exceptions. These members are indicated by a comment: // never throws.

    -

    Functions which destroy objects of the pointed to type are prohibited from +

    Functions which destroy objects of the pointed to type are prohibited from throwing exceptions by the common requirements.

    History and Acknowledgements

    -

    January 2002. Peter Dimov reworked all four classes, adding features, fixing - bugs, and splitting them into four separate headers, and added weak_ptr. - See the compatibility page for a summary of the +

    January 2002. Peter Dimov reworked all four classes, adding features, fixing + bugs, and splitting them into four separate headers, and added weak_ptr. + See the compatibility page for a summary of the changes.

    -

    May 2001. Vladimir Prus suggested requiring a complete type on destruction. - Refinement evolved in discussions including Dave Abrahams, Greg Colvin, Beman - Dawes, Rainer Deyke, Peter Dimov, John Maddock, Vladimir Prus, Shankar Sai, and +

    May 2001. Vladimir Prus suggested requiring a complete type on destruction. + Refinement evolved in discussions including Dave Abrahams, Greg Colvin, Beman + Dawes, Rainer Deyke, Peter Dimov, John Maddock, Vladimir Prus, Shankar Sai, and others.

    November 1999. Darin Adler provided operator ==, operator !=, and std::swap and std::less specializations for shared types.

    September 1999. Luis Coelho provided shared_ptr::swap and shared_array::swap

    -

    May 1999. In April and May, 1999, Valentin Bonnard and David Abrahams made a +

    May 1999. In April and May, 1999, Valentin Bonnard and David Abrahams made a number of suggestions resulting in numerous improvements.

    -

    October 1998. Beman Dawes proposed reviving the original semantics under the - names safe_ptr and counted_ptr, meeting of Per Andersson, Matt - Austern, Greg Colvin, Sean Corfield, Pete Becker, Nico Josuttis, Dietmar Kühl, - Nathan Myers, Chichiang Wan and Judy Ward. During the discussion, the four new - class names were finalized, it was decided that there was no need to exactly - follow the std::auto_ptr interface, and various function signatures and +

    October 1998. Beman Dawes proposed reviving the original semantics under the + names safe_ptr and counted_ptr, meeting of Per Andersson, Matt + Austern, Greg Colvin, Sean Corfield, Pete Becker, Nico Josuttis, Dietmar Kühl, + Nathan Myers, Chichiang Wan and Judy Ward. During the discussion, the four new + class names were finalized, it was decided that there was no need to exactly + follow the std::auto_ptr interface, and various function signatures and semantics were finalized.

    -

    Over the next three months, several implementations were considered for shared_ptr, - and discussed on the boost.org mailing list. - The implementation questions revolved around the reference count which must be - kept, either attached to the pointed to object, or detached elsewhere. Each of +

    Over the next three months, several implementations were considered for shared_ptr, + and discussed on the boost.org mailing list. + The implementation questions revolved around the reference count which must be + kept, either attached to the pointed to object, or detached elsewhere. Each of those variants have themselves two major variants:

    • - Direct detached: the shared_ptr contains a pointer to the object, and a pointer + Direct detached: the shared_ptr contains a pointer to the object, and a pointer to the count.
    • - Indirect detached: the shared_ptr contains a pointer to a helper object, which + Indirect detached: the shared_ptr contains a pointer to a helper object, which in turn contains a pointer to the object and the count.
    • Embedded attached: the count is a member of the object pointed to.
    • Placement attached: the count is attached via operator new manipulations.
    -

    Each implementation technique has advantages and disadvantages. We went so far - as to run various timings of the direct and indirect approaches, and found that - at least on Intel Pentium chips there was very little measurable difference. - Kevlin Henney provided a paper he wrote on "Counted Body Techniques." Dietmar - Kühl suggested an elegant partial template specialization technique to allow - users to choose which implementation they preferred, and that was also +

    Each implementation technique has advantages and disadvantages. We went so far + as to run various timings of the direct and indirect approaches, and found that + at least on Intel Pentium chips there was very little measurable difference. + Kevlin Henney provided a paper he wrote on "Counted Body Techniques." Dietmar + Kühl suggested an elegant partial template specialization technique to allow + users to choose which implementation they preferred, and that was also experimented with.

    -

    But Greg Colvin and Jerry Schwarz argued that "parameterization will discourage +

    But Greg Colvin and Jerry Schwarz argued that "parameterization will discourage users", and in the end we choose to supply only the direct implementation.

    Summer, 1994. Greg Colvin proposed to the C++ Standards Committee classes named auto_ptr and counted_ptr which were very similar to what we now call scoped_ptr - and shared_ptr. [Col-94] In one of the very few - cases where the Library Working Group's recommendations were not followed by - the full committee, counted_ptr was rejected and surprising + and shared_ptr. [Col-94] In one of the very few + cases where the Library Working Group's recommendations were not followed by + the full committee, counted_ptr was rejected and surprising transfer-of-ownership semantics were added to auto_ptr.

    References

    [Col-94] Gregory Colvin, - Exception Safe Smart Pointers, C++ committee document 94-168/N0555, + Exception Safe Smart Pointers, C++ committee document 94-168/N0555, July, 1994.

    [E&D-94] John R. Ellis & David L. Detlefs, - Safe, Efficient Garbage Collection for C++, Usenix Proceedings, - February, 1994. This paper includes an extensive discussion of weak pointers + Safe, Efficient Garbage Collection for C++, Usenix Proceedings, + February, 1994. This paper includes an extensive discussion of weak pointers and an extensive bibliography.


    $Date$

    -

    Copyright 1999 Greg Colvin and Beman Dawes. Copyright 2002 Darin Adler. +

    Copyright 1999 Greg Colvin and Beman Dawes. Copyright 2002 Darin Adler. Distributed under the Boost Software License, Version 1.0. See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.