1 <section xmlns="http://docbook.org/ns/docbook" version="5.0"
2 xml:id="std.util.memory.shared_ptr" xreflabel="shared_ptr">
3 <?dbhtml filename="shared_ptr.html"?>
5 <info><title>shared_ptr</title>
19 The shared_ptr class template stores a pointer, usually obtained via new,
20 and implements shared ownership semantics.
23 <section xml:id="shared_ptr.req"><info><title>Requirements</title></info>
30 The standard deliberately doesn't require a reference-counted
31 implementation, allowing other techniques such as a
36 At the time of writing the C++0x working paper doesn't mention how
37 threads affect shared_ptr, but it is likely to follow the existing
38 practice set by <classname>boost::shared_ptr</classname>. The
39 shared_ptr in libstdc++ is derived from Boost's, so the same rules
47 <section xml:id="shared_ptr.design_issues"><info><title>Design Issues</title></info>
52 The <classname>shared_ptr</classname> code is kindly donated to GCC by the Boost
53 project and the original authors of the code. The basic design and
54 algorithms are from Boost, the notes below describe details specific to
55 the GCC implementation. Names have been uglified in this implementation,
56 but the design should be recognisable to anyone familiar with the Boost
61 The basic design is an abstract base class, <code>_Sp_counted_base</code> that
62 does the reference-counting and calls virtual functions when the count
64 Derived classes override those functions to destroy resources in a context
65 where the correct dynamic type is known. This is an application of the
66 technique known as type erasure.
71 <section xml:id="shared_ptr.impl"><info><title>Implementation</title></info>
74 <section><info><title>Class Hierarchy</title></info>
78 A <classname>shared_ptr<T></classname> contains a pointer of
79 type <type>T*</type> and an object of type
80 <classname>__shared_count</classname>. The shared_count contains a
81 pointer of type <type>_Sp_counted_base*</type> which points to the
82 object that maintains the reference-counts and destroys the managed
89 <term><classname>_Sp_counted_base<Lp></classname></term>
92 The base of the hierarchy is parameterized on the lock policy (see below.)
93 _Sp_counted_base doesn't depend on the type of pointer being managed,
94 it only maintains the reference counts and calls virtual functions when
95 the counts drop to zero. The managed object is destroyed when the last
96 strong reference is dropped, but the _Sp_counted_base itself must exist
97 until the last weak reference is dropped.
103 <term><classname>_Sp_counted_base_impl<Ptr, Deleter, Lp></classname></term>
106 Inherits from _Sp_counted_base and stores a pointer of type <type>Ptr</type>
107 and a deleter of type <code>Deleter</code>. <code>_Sp_deleter</code> is
108 used when the user doesn't supply a custom deleter. Unlike Boost's, this
109 default deleter is not "checked" because GCC already issues a warning if
110 <function>delete</function> is used with an incomplete type.
111 This is the only derived type used by <classname>shared_ptr<Ptr></classname>
112 and it is never used by <classname>shared_ptr</classname>, which uses one of
113 the following types, depending on how the shared_ptr is constructed.
119 <term><classname>_Sp_counted_ptr<Ptr, Lp></classname></term>
122 Inherits from _Sp_counted_base and stores a pointer of type <type>Ptr</type>,
123 which is passed to <function>delete</function> when the last reference is dropped.
124 This is the simplest form and is used when there is no custom deleter or
131 <term><classname>_Sp_counted_deleter<Ptr, Deleter, Alloc></classname></term>
134 Inherits from _Sp_counted_ptr and adds support for custom deleter and
135 allocator. Empty Base Optimization is used for the allocator. This class
136 is used even when the user only provides a custom deleter, in which case
137 <classname>allocator</classname> is used as the allocator.
143 <term><classname>_Sp_counted_ptr_inplace<Tp, Alloc, Lp></classname></term>
146 Used by <code>allocate_shared</code> and <code>make_shared</code>.
147 Contains aligned storage to hold an object of type <type>Tp</type>,
148 which is constructed in-place with placement <function>new</function>.
149 Has a variadic template constructor allowing any number of arguments to
150 be forwarded to <type>Tp</type>'s constructor.
151 Unlike the other <classname>_Sp_counted_*</classname> classes, this one is parameterized on the
152 type of object, not the type of pointer; this is purely a convenience
153 that simplifies the implementation slightly.
162 <section><info><title>Thread Safety</title></info>
166 C++0x-only features are: rvalue-ref/move support, allocator support,
167 aliasing constructor, make_shared & allocate_shared. Additionally,
168 the constructors taking <classname>auto_ptr</classname> parameters are
169 deprecated in C++0x mode.
174 <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety">Thread
175 Safety</link> section of the Boost shared_ptr documentation says "shared_ptr
176 objects offer the same level of thread safety as built-in types."
177 The implementation must ensure that concurrent updates to separate shared_ptr
178 instances are correct even when those instances share a reference count e.g.
182 shared_ptr<A> a(new A);
183 shared_ptr<A> b(a);
185 // Thread 1 // Thread 2
186 a.reset(); b.reset();
190 The dynamically-allocated object must be destroyed by exactly one of the
191 threads. Weak references make things even more interesting.
192 The shared state used to implement shared_ptr must be transparent to the
193 user and invariants must be preserved at all times.
194 The key pieces of shared state are the strong and weak reference counts.
195 Updates to these need to be atomic and visible to all threads to ensure
196 correct cleanup of the managed resource (which is, after all, shared_ptr's
198 On multi-processor systems memory synchronisation may be needed so that
199 reference-count updates and the destruction of the managed resource are
204 The function <function>_Sp_counted_base::_M_add_ref_lock()</function>, called when
205 obtaining a shared_ptr from a weak_ptr, has to test if the managed
206 resource still exists and either increment the reference count or throw
207 <classname>bad_weak_ptr</classname>.
208 In a multi-threaded program there is a potential race condition if the last
209 reference is dropped (and the managed resource destroyed) between testing
210 the reference count and incrementing it, which could result in a shared_ptr
211 pointing to invalid memory.
214 The Boost shared_ptr (as used in GCC) features a clever lock-free
215 algorithm to avoid the race condition, but this relies on the
216 processor supporting an atomic <emphasis>Compare-And-Swap</emphasis>
217 instruction. For other platforms there are fall-backs using mutex
218 locks. Boost (as of version 1.35) includes several different
219 implementations and the preprocessor selects one based on the
220 compiler, standard library, platform etc. For the version of
221 shared_ptr in libstdc++ the compiler and library are fixed, which
222 makes things much simpler: we have an atomic CAS or we don't, see Lock
223 Policy below for details.
228 <section><info><title>Selecting Lock Policy</title></info>
235 There is a single <classname>_Sp_counted_base</classname> class,
236 which is a template parameterized on the enum
237 <type>__gnu_cxx::_Lock_policy</type>. The entire family of classes is
238 parameterized on the lock policy, right up to
239 <classname>__shared_ptr</classname>, <classname>__weak_ptr</classname> and
240 <classname>__enable_shared_from_this</classname>. The actual
241 <classname>std::shared_ptr</classname> class inherits from
242 <classname>__shared_ptr</classname> with the lock policy parameter
243 selected automatically based on the thread model and platform that
244 libstdc++ is configured for, so that the best available template
245 specialization will be used. This design is necessary because it would
246 not be conforming for <classname>shared_ptr</classname> to have an
247 extra template parameter, even if it had a default value. The
248 available policies are:
254 <type>_S_Atomic</type>
257 Selected when GCC supports a builtin atomic compare-and-swap operation
258 on the target processor (see <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html">Atomic
259 Builtins</link>.) The reference counts are maintained using a lock-free
260 algorithm and GCC's atomic builtins, which provide the required memory
267 <type>_S_Mutex</type>
270 The _Sp_counted_base specialization for this policy contains a mutex,
271 which is locked in add_ref_lock(). This policy is used when GCC's atomic
272 builtins aren't available so explicit memory barriers are needed in places.
278 <type>_S_Single</type>
281 This policy uses a non-reentrant add_ref_lock() with no locking. It is
282 used when libstdc++ is built without <literal>--enable-threads</literal>.
288 For all three policies, reference count increments and
289 decrements are done via the functions in
290 <filename>ext/atomicity.h</filename>, which detect if the program
291 is multi-threaded. If only one thread of execution exists in
292 the program then less expensive non-atomic operations are used.
296 <section><info><title>Dual C++0x and TR1 Implementation</title></info>
300 The interface of <classname>tr1::shared_ptr</classname> was extended for C++0x
301 with support for rvalue-references and the other features from N2351.
302 The <classname>_Sp_counted_base</classname> base class is implemented in
303 <filename>tr1/boost_sp_shared_count.h</filename> and is common to the TR1
304 and C++0x versions of <classname>shared_ptr</classname>.
308 The classes derived from <classname>_Sp_counted_base</classname> (see Class Hierarchy
309 above) and <classname>__shared_count</classname> are implemented separately for C++0x
310 and TR1, in <filename>bits/shared_ptr.h</filename> and
311 <filename>tr1/shared_ptr.h</filename> respectively.
315 The TR1 implementation is considered relatively stable, so is unlikely to
316 change unless bug fixes require it. If the code that is common to both
317 C++0x and TR1 modes needs to diverge further then it might be necessary to
318 duplicate <classname>_Sp_counted_base</classname> and only make changes to
323 <section><info><title>Related functions and classes</title></info>
329 <term><code>dynamic_pointer_cast</code>, <code>static_pointer_cast</code>,
330 <code>const_pointer_cast</code></term>
333 As noted in N2351, these functions can be implemented non-intrusively using
334 the alias constructor. However the aliasing constructor is only available
335 in C++0x mode, so in TR1 mode these casts rely on three non-standard
336 constructors in shared_ptr and __shared_ptr.
337 In C++0x mode these constructors and the related tag types are not needed.
343 <term><code>enable_shared_from_this</code></term>
346 The clever overload to detect a base class of type
347 <code>enable_shared_from_this</code> comes straight from Boost.
348 There is an extra overload for <code>__enable_shared_from_this</code> to
349 work smoothly with <code>__shared_ptr<Tp, Lp></code> using any lock
356 <term><code>make_shared</code>, <code>allocate_shared</code></term>
359 <code>make_shared</code> simply forwards to <code>allocate_shared</code>
360 with <code>std::allocator</code> as the allocator.
361 Although these functions can be implemented non-intrusively using the
362 alias constructor, if they have access to the implementation then it is
363 possible to save storage and reduce the number of heap allocations. The
364 newly constructed object and the _Sp_counted_* can be allocated in a single
365 block and the standard says implementations are "encouraged, but not required,"
366 to do so. This implementation provides additional non-standard constructors
367 (selected with the type <code>_Sp_make_shared_tag</code>) which create an
368 object of type <code>_Sp_counted_ptr_inplace</code> to hold the new object.
369 The returned <code>shared_ptr<A></code> needs to know the address of the
370 new <code>A</code> object embedded in the <code>_Sp_counted_ptr_inplace</code>,
371 but it has no way to access it.
372 This implementation uses a "covert channel" to return the address of the
373 embedded object when <code>get_deleter<_Sp_make_shared_tag>()</code>
374 is called. Users should not try to use this.
375 As well as the extra constructors, this implementation also needs some
376 members of _Sp_counted_deleter to be protected where they could otherwise
390 <type>_Sp_counted_base<Lp></type>
392 The base of the hierarchy is parameterized on the lock policy alone.
393 _Sp_counted_base doesn't depend on the type of pointer being managed,
394 it only maintains the reference counts and calls virtual functions when
395 the counts drop to zero. The managed object is destroyed when the last
396 strong reference is dropped, but the _Sp_counted_base itself must exist
397 until the last weak reference is dropped.
402 <type>_Sp_counted_base_impl<Ptr, Deleter, Lp></type>
404 Inherits from _Sp_counted_base and stores a pointer of type <code>Ptr</code>
405 and a deleter of type <code>Deleter</code>. <code>_Sp_deleter</code> is
406 used when the user doesn't supply a custom deleter. Unlike Boost's, this
407 default deleter is not "checked" because GCC already issues a warning if
408 <code>delete</code> is used with an incomplete type.
409 This is the only derived type used by <code>tr1::shared_ptr<Ptr></code>
410 and it is never used by <code>std::shared_ptr</code>, which uses one of
411 the following types, depending on how the shared_ptr is constructed.
416 <section xml:id="shared_ptr.using"><info><title>Use</title></info>
419 <section><info><title>Examples</title></info>
422 Examples of use can be found in the testsuite, under
423 <filename class="directory">testsuite/tr1/2_general_utilities/shared_ptr</filename>,
424 <filename class="directory">testsuite/20_util/shared_ptr</filename>
426 <filename class="directory">testsuite/20_util/weak_ptr</filename>.
430 <section><info><title>Unresolved Issues</title></info>
433 The <emphasis><classname>shared_ptr</classname> atomic access</emphasis>
434 clause in the C++0x working draft is not implemented in GCC.
438 The <type>_S_single</type> policy uses atomics when used in MT
439 code, because it uses the same dispatcher functions that check
440 <function>__gthread_active_p()</function>. This could be
441 addressed by providing template specialisations for some members
442 of <classname>_Sp_counted_base<_S_single></classname>.
446 Unlike Boost, this implementation does not use separate classes
447 for the pointer+deleter and pointer+deleter+allocator cases in
448 C++0x mode, combining both into _Sp_counted_deleter and using
449 <classname>allocator</classname> when the user doesn't specify
450 an allocator. If it was found to be beneficial an additional
451 class could easily be added. With the current implementation,
452 the _Sp_counted_deleter and __shared_count constructors taking a
453 custom deleter but no allocator are technically redundant and
454 could be removed, changing callers to always specify an
455 allocator. If a separate pointer+deleter class was added the
456 __shared_count constructor would be needed, so it has been kept
461 The hack used to get the address of the managed object from
462 <function>_Sp_counted_ptr_inplace::_M_get_deleter()</function>
463 is accessible to users. This could be prevented if
464 <function>get_deleter<_Sp_make_shared_tag>()</function>
465 always returned NULL, since the hack only needs to work at a
466 lower level, not in the public API. This wouldn't be difficult,
467 but hasn't been done since there is no danger of accidental
468 misuse: users already know they are relying on unsupported
469 features if they refer to implementation details such as
474 tr1::_Sp_deleter could be a private member of tr1::__shared_count but it
482 <section xml:id="shared_ptr.ack"><info><title>Acknowledgments</title></info>
486 The original authors of the Boost shared_ptr, which is really nice
487 code to work with, Peter Dimov in particular for his help and
488 invaluable advice on thread safety. Phillip Jordan and Paolo
489 Carlini for the lock policy implementation.
494 <bibliography xml:id="shared_ptr.biblio"><info><title>Bibliography</title></info>
498 <biblioid xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm" class="uri">
501 Improving shared_ptr for C++0x, Revision 2
509 <biblioid xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html" class="uri">
512 C++ Standard Library Active Issues List
520 <biblioid xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf" class="uri">
523 Working Draft, Standard for Programming Language C++
531 <biblioid xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://boost.org/libs/smart_ptr/shared_ptr.htm" class="uri">shared_ptr
534 Boost C++ Libraries documentation, shared_ptr