| <?xml version="1.0" encoding="UTF-8" standalone="no"?> |
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| <html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>shared_ptr</title><meta name="generator" content="DocBook XSL Stylesheets V1.74.0" /><meta name="keywords" content=" ISO C++ , shared_ptr " /><meta name="keywords" content=" ISO C++ , library " /><link rel="home" href="../spine.html" title="The GNU C++ Library Documentation" /><link rel="up" href="memory.html" title="Chapter 11. Memory" /><link rel="prev" href="auto_ptr.html" title="auto_ptr" /><link rel="next" href="traits.html" title="Chapter 12. Traits" /></head><body><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">shared_ptr</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="auto_ptr.html">Prev</a> </td><th width="60%" align="center">Chapter 11. Memory</th><td width="20%" align="right"> <a accesskey="n" href="traits.html">Next</a></td></tr></table><hr /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="manual.util.memory.shared_ptr"></a>shared_ptr</h2></div></div></div><p> |
| The shared_ptr class template stores a pointer, usually obtained via new, |
| and implements shared ownership semantics. |
| </p><div class="sect2" lang="en" xml:lang="en"><div class="titlepage"><div><div><h3 class="title"><a id="shared_ptr.req"></a>Requirements</h3></div></div></div><p> |
| </p><p> |
| The standard deliberately doesn't require a reference-counted |
| implementation, allowing other techniques such as a |
| circular-linked-list. |
| </p><p> |
| At the time of writing the C++0x working paper doesn't mention how |
| threads affect shared_ptr, but it is likely to follow the existing |
| practice set by <code class="classname">boost::shared_ptr</code>. The |
| shared_ptr in libstdc++ is derived from Boost's, so the same rules |
| apply. |
| </p><p> |
| </p></div><div class="sect2" lang="en" xml:lang="en"><div class="titlepage"><div><div><h3 class="title"><a id="shared_ptr.design_issues"></a>Design Issues</h3></div></div></div><p> |
| The <code class="classname">shared_ptr</code> code is kindly donated to GCC by the Boost |
| project and the original authors of the code. The basic design and |
| algorithms are from Boost, the notes below describe details specific to |
| the GCC implementation. Names have been uglified in this implementation, |
| but the design should be recognisable to anyone familiar with the Boost |
| 1.32 shared_ptr. |
| </p><p> |
| The basic design is an abstract base class, <code class="code">_Sp_counted_base</code> that |
| does the reference-counting and calls virtual functions when the count |
| drops to zero. |
| Derived classes override those functions to destroy resources in a context |
| where the correct dynamic type is known. This is an application of the |
| technique known as type erasure. |
| </p></div><div class="sect2" lang="en" xml:lang="en"><div class="titlepage"><div><div><h3 class="title"><a id="shared_ptr.impl"></a>Implementation</h3></div></div></div><div class="sect3" lang="en" xml:lang="en"><div class="titlepage"><div><div><h4 class="title"><a id="id400915"></a>Class Hierarchy</h4></div></div></div><p> |
| A <code class="classname">shared_ptr<T></code> contains a pointer of |
| type <span class="type">T*</span> and an object of type |
| <code class="classname">__shared_count</code>. The shared_count contains a |
| pointer of type <span class="type">_Sp_counted_base*</span> which points to the |
| object that maintains the reference-counts and destroys the managed |
| resource. |
| </p><div class="variablelist"><dl><dt><span class="term"><code class="classname">_Sp_counted_base<Lp></code></span></dt><dd><p> |
| The base of the hierarchy is parameterized on the lock policy alone. |
| _Sp_counted_base doesn't depend on the type of pointer being managed, |
| it only maintains the reference counts and calls virtual functions when |
| the counts drop to zero. The managed object is destroyed when the last |
| strong reference is dropped, but the _Sp_counted_base itself must exist |
| until the last weak reference is dropped. |
| </p></dd><dt><span class="term"><code class="classname">_Sp_counted_base_impl<Ptr, Deleter, Lp></code></span></dt><dd><p> |
| Inherits from _Sp_counted_base and stores a pointer of type <span class="type">Ptr</span> |
| and a deleter of type <code class="code">Deleter</code>. <code class="code">_Sp_deleter</code> is |
| used when the user doesn't supply a custom deleter. Unlike Boost's, this |
| default deleter is not "checked" because GCC already issues a warning if |
| <code class="function">delete</code> is used with an incomplete type. |
| This is the only derived type used by <code class="classname">shared_ptr<Ptr></code> |
| and it is never used by <code class="classname">shared_ptr</code>, which uses one of |
| the following types, depending on how the shared_ptr is constructed. |
| </p></dd><dt><span class="term"><code class="classname">_Sp_counted_ptr<Ptr, Lp></code></span></dt><dd><p> |
| Inherits from _Sp_counted_base and stores a pointer of type <span class="type">Ptr</span>, |
| which is passed to <code class="function">delete</code> when the last reference is dropped. |
| This is the simplest form and is used when there is no custom deleter or |
| allocator. |
| </p></dd><dt><span class="term"><code class="classname">_Sp_counted_deleter<Ptr, Deleter, Alloc></code></span></dt><dd><p> |
| Inherits from _Sp_counted_ptr and adds support for custom deleter and |
| allocator. Empty Base Optimization is used for the allocator. This class |
| is used even when the user only provides a custom deleter, in which case |
| <code class="classname">allocator</code> is used as the allocator. |
| </p></dd><dt><span class="term"><code class="classname">_Sp_counted_ptr_inplace<Tp, Alloc, Lp></code></span></dt><dd><p> |
| Used by <code class="code">allocate_shared</code> and <code class="code">make_shared</code>. |
| Contains aligned storage to hold an object of type <span class="type">Tp</span>, |
| which is constructed in-place with placement <code class="function">new</code>. |
| Has a variadic template constructor allowing any number of arguments to |
| be forwarded to <span class="type">Tp</span>'s constructor. |
| Unlike the other <code class="classname">_Sp_counted_*</code> classes, this one is parameterized on the |
| type of object, not the type of pointer; this is purely a convenience |
| that simplifies the implementation slightly. |
| </p></dd></dl></div></div><div class="sect3" lang="en" xml:lang="en"><div class="titlepage"><div><div><h4 class="title"><a id="id407287"></a>Thread Safety</h4></div></div></div><p> |
| The interface of <code class="classname">tr1::shared_ptr</code> was extended for C++0x |
| with support for rvalue-references and the other features from |
| N2351. As with other libstdc++ headers shared by TR1 and C++0x, |
| boost_shared_ptr.h uses conditional compilation, based on the macros |
| <code class="constant">_GLIBCXX_INCLUDE_AS_CXX0X</code> and |
| <code class="constant">_GLIBCXX_INCLUDE_AS_TR1</code>, to enable and disable |
| features. |
| </p><p> |
| C++0x-only features are: rvalue-ref/move support, allocator support, |
| aliasing constructor, make_shared & allocate_shared. Additionally, |
| the constructors taking <code class="classname">auto_ptr</code> parameters are |
| deprecated in C++0x mode. |
| </p><p> |
| The |
| <a class="ulink" href="http://boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety" target="_top">Thread |
| Safety</a> section of the Boost shared_ptr documentation says "shared_ptr |
| objects offer the same level of thread safety as built-in types." |
| The implementation must ensure that concurrent updates to separate shared_ptr |
| instances are correct even when those instances share a reference count e.g. |
| </p><pre class="programlisting"> |
| shared_ptr<A> a(new A); |
| shared_ptr<A> b(a); |
| |
| // Thread 1 // Thread 2 |
| a.reset(); b.reset(); |
| </pre><p> |
| The dynamically-allocated object must be destroyed by exactly one of the |
| threads. Weak references make things even more interesting. |
| The shared state used to implement shared_ptr must be transparent to the |
| user and invariants must be preserved at all times. |
| The key pieces of shared state are the strong and weak reference counts. |
| Updates to these need to be atomic and visible to all threads to ensure |
| correct cleanup of the managed resource (which is, after all, shared_ptr's |
| job!) |
| On multi-processor systems memory synchronisation may be needed so that |
| reference-count updates and the destruction of the managed resource are |
| race-free. |
| </p><p> |
| The function <code class="function">_Sp_counted_base::_M_add_ref_lock()</code>, called when |
| obtaining a shared_ptr from a weak_ptr, has to test if the managed |
| resource still exists and either increment the reference count or throw |
| <code class="classname">bad_weak_ptr</code>. |
| In a multi-threaded program there is a potential race condition if the last |
| reference is dropped (and the managed resource destroyed) between testing |
| the reference count and incrementing it, which could result in a shared_ptr |
| pointing to invalid memory. |
| </p><p> |
| The Boost shared_ptr (as used in GCC) features a clever lock-free |
| algorithm to avoid the race condition, but this relies on the |
| processor supporting an atomic <span class="emphasis"><em>Compare-And-Swap</em></span> |
| instruction. For other platforms there are fall-backs using mutex |
| locks. Boost (as of version 1.35) includes several different |
| implementations and the preprocessor selects one based on the |
| compiler, standard library, platform etc. For the version of |
| shared_ptr in libstdc++ the compiler and library are fixed, which |
| makes things much simpler: we have an atomic CAS or we don't, see Lock |
| Policy below for details. |
| </p></div><div class="sect3" lang="en" xml:lang="en"><div class="titlepage"><div><div><h4 class="title"><a id="id402403"></a>Selecting Lock Policy</h4></div></div></div><p> |
| </p><p> |
| There is a single <code class="classname">_Sp_counted_base</code> class, |
| which is a template parameterized on the enum |
| <span class="type">__gnu_cxx::_Lock_policy</span>. The entire family of classes is |
| parameterized on the lock policy, right up to |
| <code class="classname">__shared_ptr</code>, <code class="classname">__weak_ptr</code> and |
| <code class="classname">__enable_shared_from_this</code>. The actual |
| <code class="classname">std::shared_ptr</code> class inherits from |
| <code class="classname">__shared_ptr</code> with the lock policy parameter |
| selected automatically based on the thread model and platform that |
| libstdc++ is configured for, so that the best available template |
| specialization will be used. This design is necessary because it would |
| not be conforming for <code class="classname">shared_ptr</code> to have an |
| extra template parameter, even if it had a default value. The |
| available policies are: |
| </p><div class="orderedlist"><ol type="1"><li><p> |
| <span class="type">_S_Atomic</span> |
| </p><p> |
| Selected when GCC supports a builtin atomic compare-and-swap operation |
| on the target processor (see <a class="ulink" href="http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html" target="_top">Atomic |
| Builtins</a>.) The reference counts are maintained using a lock-free |
| algorithm and GCC's atomic builtins, which provide the required memory |
| synchronisation. |
| </p></li><li><p> |
| <span class="type">_S_Mutex</span> |
| </p><p> |
| The _Sp_counted_base specialization for this policy contains a mutex, |
| which is locked in add_ref_lock(). This policy is used when GCC's atomic |
| builtins aren't available so explicit memory barriers are needed in places. |
| </p></li><li><p> |
| <span class="type">_S_Single</span> |
| </p><p> |
| This policy uses a non-reentrant add_ref_lock() with no locking. It is |
| used when libstdc++ is built without <code class="literal">--enable-threads</code>. |
| </p></li></ol></div><p> |
| For all three policies, reference count increments and |
| decrements are done via the functions in |
| <code class="filename">ext/atomicity.h</code>, which detect if the program |
| is multi-threaded. If only one thread of execution exists in |
| the program then less expensive non-atomic operations are used. |
| </p></div><div class="sect3" lang="en" xml:lang="en"><div class="titlepage"><div><div><h4 class="title"><a id="id406621"></a>Dual C++0x and TR1 Implementation</h4></div></div></div><p> |
| The classes derived from <code class="classname">_Sp_counted_base</code> (see Class Hierarchy |
| below) and <code class="classname">__shared_count</code> are implemented separately for C++0x |
| and TR1, in <code class="filename">bits/boost_sp_shared_count.h</code> and |
| <code class="filename">tr1/boost_sp_shared_count.h</code> respectively. All other classes |
| including <code class="classname">_Sp_counted_base</code> are shared by both implementations. |
| </p><p> |
| The TR1 implementation is considered relatively stable, so is unlikely to |
| change unless bug fixes require it. If the code that is common to both |
| C++0x and TR1 modes needs to diverge further then it might be necessary to |
| duplicate additional classes and only make changes to the C++0x versions. |
| </p></div><div class="sect3" lang="en" xml:lang="en"><div class="titlepage"><div><div><h4 class="title"><a id="id396482"></a>Related functions and classes</h4></div></div></div><div class="variablelist"><dl><dt><span class="term"><code class="code">dynamic_pointer_cast</code>, <code class="code">static_pointer_cast</code>, |
| <code class="code">const_pointer_cast</code></span></dt><dd><p> |
| As noted in N2351, these functions can be implemented non-intrusively using |
| the alias constructor. However the aliasing constructor is only available |
| in C++0x mode, so in TR1 mode these casts rely on three non-standard |
| constructors in shared_ptr and __shared_ptr. |
| In C++0x mode these constructors and the related tag types are not needed. |
| </p></dd><dt><span class="term"><code class="code">enable_shared_from_this</code></span></dt><dd><p> |
| The clever overload to detect a base class of type |
| <code class="code">enable_shared_from_this</code> comes straight from Boost. |
| There is an extra overload for <code class="code">__enable_shared_from_this</code> to |
| work smoothly with <code class="code">__shared_ptr<Tp, Lp></code> using any lock |
| policy. |
| </p></dd><dt><span class="term"><code class="code">make_shared</code>, <code class="code">allocate_shared</code></span></dt><dd><p> |
| <code class="code">make_shared</code> simply forwards to <code class="code">allocate_shared</code> |
| with <code class="code">std::allocator</code> as the allocator. |
| Although these functions can be implemented non-intrusively using the |
| alias constructor, if they have access to the implementation then it is |
| possible to save storage and reduce the number of heap allocations. The |
| newly constructed object and the _Sp_counted_* can be allocated in a single |
| block and the standard says implementations are "encouraged, but not required," |
| to do so. This implementation provides additional non-standard constructors |
| (selected with the type <code class="code">_Sp_make_shared_tag</code>) which create an |
| object of type <code class="code">_Sp_counted_ptr_inplace</code> to hold the new object. |
| The returned <code class="code">shared_ptr<A></code> needs to know the address of the |
| new <code class="code">A</code> object embedded in the <code class="code">_Sp_counted_ptr_inplace</code>, |
| but it has no way to access it. |
| This implementation uses a "covert channel" to return the address of the |
| embedded object when <code class="code">get_deleter<_Sp_make_shared_tag>()</code> |
| is called. Users should not try to use this. |
| As well as the extra constructors, this implementation also needs some |
| members of _Sp_counted_deleter to be protected where they could otherwise |
| be private. |
| </p></dd></dl></div></div></div><div class="sect2" lang="en" xml:lang="en"><div class="titlepage"><div><div><h3 class="title"><a id="shared_ptr.using"></a>Use</h3></div></div></div><div class="sect3" lang="en" xml:lang="en"><div class="titlepage"><div><div><h4 class="title"><a id="id397112"></a>Examples</h4></div></div></div><p> |
| Examples of use can be found in the testsuite, under |
| <code class="filename">testsuite/tr1/2_general_utilities/shared_ptr</code>. |
| </p></div><div class="sect3" lang="en" xml:lang="en"><div class="titlepage"><div><div><h4 class="title"><a id="id403999"></a>Unresolved Issues</h4></div></div></div><p> |
| The resolution to C++ Standard Library issue <a class="ulink" href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#674" target="_top">674</a>, |
| "shared_ptr interface changes for consistency with N1856" will |
| need to be implemented after it is accepted into the working |
| paper. Issue <a class="ulink" href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#743" target="_top">743</a> |
| might also require changes. |
| </p><p> |
| The <span class="type">_S_single</span> policy uses atomics when used in MT |
| code, because it uses the same dispatcher functions that check |
| <code class="function">__gthread_active_p()</code>. This could be |
| addressed by providing template specialisations for some members |
| of <code class="classname">_Sp_counted_base<_S_single></code>. |
| </p><p> |
| Unlike Boost, this implementation does not use separate classes |
| for the pointer+deleter and pointer+deleter+allocator cases in |
| C++0x mode, combining both into _Sp_counted_deleter and using |
| <code class="classname">allocator</code> when the user doesn't specify |
| an allocator. If it was found to be beneficial an additional |
| class could easily be added. With the current implementation, |
| the _Sp_counted_deleter and __shared_count constructors taking a |
| custom deleter but no allocator are technically redundant and |
| could be removed, changing callers to always specify an |
| allocator. If a separate pointer+deleter class was added the |
| __shared_count constructor would be needed, so it has been kept |
| for now. |
| </p><p> |
| The hack used to get the address of the managed object from |
| <code class="function">_Sp_counted_ptr_inplace::_M_get_deleter()</code> |
| is accessible to users. This could be prevented if |
| <code class="function">get_deleter<_Sp_make_shared_tag>()</code> |
| always returned NULL, since the hack only needs to work at a |
| lower level, not in the public API. This wouldn't be difficult, |
| but hasn't been done since there is no danger of accidental |
| misuse: users already know they are relying on unsupported |
| features if they refer to implementation details such as |
| _Sp_make_shared_tag. |
| </p><p> |
| tr1::_Sp_deleter could be a private member of tr1::__shared_count but it |
| would alter the ABI. |
| </p><p> |
| Exposing the alias constructor in TR1 mode could simplify the |
| *_pointer_cast functions. Constructor could be private in TR1 |
| mode, with the cast functions as friends. |
| </p></div></div><div class="sect2" lang="en" xml:lang="en"><div class="titlepage"><div><div><h3 class="title"><a id="shared_ptr.ack"></a>Acknowledgments</h3></div></div></div><p> |
| The original authors of the Boost shared_ptr, which is really nice |
| code to work with, Peter Dimov in particular for his help and |
| invaluable advice on thread safety. Phillip Jordan and Paolo |
| Carlini for the lock policy implementation. |
| </p></div><div class="bibliography"><div class="titlepage"><div><div><h3 class="title"><a id="shared_ptr.biblio"></a>Bibliography</h3></div></div></div><div class="biblioentry"><a id="id399126"></a><p>[<abbr class="abbrev"> |
| n2351 |
| </abbr>] <span class="title"><i> |
| Improving shared_ptr for C++0x, Revision 2 |
| </i>. </span><span class="subtitle"> |
| N2351 |
| . </span><span class="biblioid"> |
| <a class="ulink" href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm" target="_top"> |
| </a> |
| . </span></p></div><div class="biblioentry"><a id="id406438"></a><p>[<abbr class="abbrev"> |
| n2456 |
| </abbr>] <span class="title"><i> |
| C++ Standard Library Active Issues List (Revision R52) |
| </i>. </span><span class="subtitle"> |
| N2456 |
| . </span><span class="biblioid"> |
| <a class="ulink" href="http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html" target="_top"> |
| </a> |
| . </span></p></div><div class="biblioentry"><a id="id406462"></a><p>[<abbr class="abbrev"> |
| n2461 |
| </abbr>] <span class="title"><i> |
| Working Draft, Standard for Programming Language C++ |
| </i>. </span><span class="subtitle"> |
| N2461 |
| . </span><span class="biblioid"> |
| <a class="ulink" href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf" target="_top"> |
| </a> |
| . </span></p></div><div class="biblioentry"><a id="id413273"></a><p>[<abbr class="abbrev"> |
| boostshared_ptr |
| </abbr>] <span class="title"><i> |
| Boost C++ Libraries documentation - shared_ptr class template |
| </i>. </span><span class="subtitle"> |
| N2461 |
| . </span><span class="biblioid"> |
| <a class="ulink" href="http://boost.org/libs/smart_ptr/shared_ptr.htm" target="_top">shared_ptr |
| </a> |
| . </span></p></div></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="auto_ptr.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="memory.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="traits.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">auto_ptr </td><td width="20%" align="center"><a accesskey="h" href="../spine.html">Home</a></td><td width="40%" align="right" valign="top"> Chapter 12. Traits</td></tr></table></div></body></html> |