1 <sect1 id="manual.util.memory.shared_ptr" xreflabel="shared_ptr">
2 <?dbhtml filename="shared_ptr.html"?>
15 <title>shared_ptr</title>
18 The shared_ptr class template stores a pointer, usually obtained via new,
19 and implements shared ownership semantics.
22 <sect2 id="shared_ptr.req">
23 <title>Requirements</title>
29 The standard deliberately doesn't require a reference-counted
30 implementation, allowing other techniques such as a
35 At the time of writing the C++0x working paper doesn't mention how
36 threads affect shared_ptr, but it is likely to follow the existing
37 practice set by <classname>boost::shared_ptr</classname>. The
38 shared_ptr in libstdc++ is derived from Boost's, so the same rules
46 <sect2 id="shared_ptr.design_issues">
47 <title>Design Issues</title>
51 The <classname>shared_ptr</classname> code is kindly donated to GCC by the Boost
52 project and the original authors of the code. The basic design and
53 algorithms are from Boost, the notes below describe details specific to
54 the GCC implementation. Names have been uglified in this implementation,
55 but the design should be recognisable to anyone familiar with the Boost
60 The basic design is an abstract base class, <code>_Sp_counted_base</code> that
61 does the reference-counting and calls virtual functions when the count
63 Derived classes override those functions to destroy resources in a context
64 where the correct dynamic type is known. This is an application of the
65 technique known as type erasure.
70 <sect2 id="shared_ptr.impl">
71 <title>Implementation</title>
74 <title>Class Hierarchy</title>
77 A <classname>shared_ptr<T></classname> contains a pointer of
78 type <type>T*</type> and an object of type
79 <classname>__shared_count</classname>. The shared_count contains a
80 pointer of type <type>_Sp_counted_base*</type> which points to the
81 object that maintains the reference-counts and destroys the managed
88 <term><classname>_Sp_counted_base<Lp></classname></term>
91 The base of the hierarchy is parameterized on the lock policy alone.
92 _Sp_counted_base doesn't depend on the type of pointer being managed,
93 it only maintains the reference counts and calls virtual functions when
94 the counts drop to zero. The managed object is destroyed when the last
95 strong reference is dropped, but the _Sp_counted_base itself must exist
96 until the last weak reference is dropped.
102 <term><classname>_Sp_counted_base_impl<Ptr, Deleter, Lp></classname></term>
105 Inherits from _Sp_counted_base and stores a pointer of type <type>Ptr</type>
106 and a deleter of type <code>Deleter</code>. <code>_Sp_deleter</code> is
107 used when the user doesn't supply a custom deleter. Unlike Boost's, this
108 default deleter is not "checked" because GCC already issues a warning if
109 <function>delete</function> is used with an incomplete type.
110 This is the only derived type used by <classname>shared_ptr<Ptr></classname>
111 and it is never used by <classname>shared_ptr</classname>, which uses one of
112 the following types, depending on how the shared_ptr is constructed.
118 <term><classname>_Sp_counted_ptr<Ptr, Lp></classname></term>
121 Inherits from _Sp_counted_base and stores a pointer of type <type>Ptr</type>,
122 which is passed to <function>delete</function> when the last reference is dropped.
123 This is the simplest form and is used when there is no custom deleter or
130 <term><classname>_Sp_counted_deleter<Ptr, Deleter, Alloc></classname></term>
133 Inherits from _Sp_counted_ptr and adds support for custom deleter and
134 allocator. Empty Base Optimization is used for the allocator. This class
135 is used even when the user only provides a custom deleter, in which case
136 <classname>allocator</classname> is used as the allocator.
142 <term><classname>_Sp_counted_ptr_inplace<Tp, Alloc, Lp></classname></term>
145 Used by <code>allocate_shared</code> and <code>make_shared</code>.
146 Contains aligned storage to hold an object of type <type>Tp</type>,
147 which is constructed in-place with placement <function>new</function>.
148 Has a variadic template constructor allowing any number of arguments to
149 be forwarded to <type>Tp</type>'s constructor.
150 Unlike the other <classname>_Sp_counted_*</classname> classes, this one is parameterized on the
151 type of object, not the type of pointer; this is purely a convenience
152 that simplifies the implementation slightly.
162 <title>Thread Safety</title>
165 The interface of <classname>tr1::shared_ptr</classname> was extended for C++0x
166 with support for rvalue-references and the other features from
167 N2351. As with other libstdc++ headers shared by TR1 and C++0x,
168 boost_shared_ptr.h uses conditional compilation, based on the macros
169 <constant>_GLIBCXX_INCLUDE_AS_CXX0X</constant> and
170 <constant>_GLIBCXX_INCLUDE_AS_TR1</constant>, to enable and disable
175 C++0x-only features are: rvalue-ref/move support, allocator support,
176 aliasing constructor, make_shared & allocate_shared. Additionally,
177 the constructors taking <classname>auto_ptr</classname> parameters are
178 deprecated in C++0x mode.
183 <ulink url="http://boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety">Thread
184 Safety</ulink> section of the Boost shared_ptr documentation says "shared_ptr
185 objects offer the same level of thread safety as built-in types."
186 The implementation must ensure that concurrent updates to separate shared_ptr
187 instances are correct even when those instances share a reference count e.g.
191 shared_ptr<A> a(new A);
192 shared_ptr<A> b(a);
194 // Thread 1 // Thread 2
195 a.reset(); b.reset();
199 The dynamically-allocated object must be destroyed by exactly one of the
200 threads. Weak references make things even more interesting.
201 The shared state used to implement shared_ptr must be transparent to the
202 user and invariants must be preserved at all times.
203 The key pieces of shared state are the strong and weak reference counts.
204 Updates to these need to be atomic and visible to all threads to ensure
205 correct cleanup of the managed resource (which is, after all, shared_ptr's
207 On multi-processor systems memory synchronisation may be needed so that
208 reference-count updates and the destruction of the managed resource are
213 The function <function>_Sp_counted_base::_M_add_ref_lock()</function>, called when
214 obtaining a shared_ptr from a weak_ptr, has to test if the managed
215 resource still exists and either increment the reference count or throw
216 <classname>bad_weak_ptr</classname>.
217 In a multi-threaded program there is a potential race condition if the last
218 reference is dropped (and the managed resource destroyed) between testing
219 the reference count and incrementing it, which could result in a shared_ptr
220 pointing to invalid memory.
223 The Boost shared_ptr (as used in GCC) features a clever lock-free
224 algorithm to avoid the race condition, but this relies on the
225 processor supporting an atomic <emphasis>Compare-And-Swap</emphasis>
226 instruction. For other platforms there are fall-backs using mutex
227 locks. Boost (as of version 1.35) includes several different
228 implementations and the preprocessor selects one based on the
229 compiler, standard library, platform etc. For the version of
230 shared_ptr in libstdc++ the compiler and library are fixed, which
231 makes things much simpler: we have an atomic CAS or we don't, see Lock
232 Policy below for details.
238 <title>Selecting Lock Policy</title>
244 There is a single <classname>_Sp_counted_base</classname> class,
245 which is a template parameterized on the enum
246 <type>__gnu_cxx::_Lock_policy</type>. The entire family of classes is
247 parameterized on the lock policy, right up to
248 <classname>__shared_ptr</classname>, <classname>__weak_ptr</classname> and
249 <classname>__enable_shared_from_this</classname>. The actual
250 <classname>std::shared_ptr</classname> class inherits from
251 <classname>__shared_ptr</classname> with the lock policy parameter
252 selected automatically based on the thread model and platform that
253 libstdc++ is configured for, so that the best available template
254 specialization will be used. This design is necessary because it would
255 not be conforming for <classname>shared_ptr</classname> to have an
256 extra template parameter, even if it had a default value. The
257 available policies are:
263 <type>_S_Atomic</type>
266 Selected when GCC supports a builtin atomic compare-and-swap operation
267 on the target processor (see <ulink url="http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html">Atomic
268 Builtins</ulink>.) The reference counts are maintained using a lock-free
269 algorithm and GCC's atomic builtins, which provide the required memory
276 <type>_S_Mutex</type>
279 The _Sp_counted_base specialization for this policy contains a mutex,
280 which is locked in add_ref_lock(). This policy is used when GCC's atomic
281 builtins aren't available so explicit memory barriers are needed in places.
287 <type>_S_Single</type>
290 This policy uses a non-reentrant add_ref_lock() with no locking. It is
291 used when libstdc++ is built without <literal>--enable-threads</literal>.
297 For all three policies, reference count increments and
298 decrements are done via the functions in
299 <filename>ext/atomicity.h</filename>, which detect if the program
300 is multi-threaded. If only one thread of execution exists in
301 the program then less expensive non-atomic operations are used.
306 <title>Dual C++0x and TR1 Implementation</title>
309 The classes derived from <classname>_Sp_counted_base</classname> (see Class Hierarchy
310 below) and <classname>__shared_count</classname> are implemented separately for C++0x
311 and TR1, in <filename>bits/boost_sp_shared_count.h</filename> and
312 <filename>tr1/boost_sp_shared_count.h</filename> respectively. All other classes
313 including <classname>_Sp_counted_base</classname> are shared by both implementations.
317 The TR1 implementation is considered relatively stable, so is unlikely to
318 change unless bug fixes require it. If the code that is common to both
319 C++0x and TR1 modes needs to diverge further then it might be necessary to
320 duplicate additional classes and only make changes to the C++0x versions.
325 <title>Related functions and classes</title>
330 <term><code>dynamic_pointer_cast</code>, <code>static_pointer_cast</code>,
331 <code>const_pointer_cast</code></term>
334 As noted in N2351, these functions can be implemented non-intrusively using
335 the alias constructor. However the aliasing constructor is only available
336 in C++0x mode, so in TR1 mode these casts rely on three non-standard
337 constructors in shared_ptr and __shared_ptr.
338 In C++0x mode these constructors and the related tag types are not needed.
344 <term><code>enable_shared_from_this</code></term>
347 The clever overload to detect a base class of type
348 <code>enable_shared_from_this</code> comes straight from Boost.
349 There is an extra overload for <code>__enable_shared_from_this</code> to
350 work smoothly with <code>__shared_ptr<Tp, Lp></code> using any lock
357 <term><code>make_shared</code>, <code>allocate_shared</code></term>
360 <code>make_shared</code> simply forwards to <code>allocate_shared</code>
361 with <code>std::allocator</code> as the allocator.
362 Although these functions can be implemented non-intrusively using the
363 alias constructor, if they have access to the implementation then it is
364 possible to save storage and reduce the number of heap allocations. The
365 newly constructed object and the _Sp_counted_* can be allocated in a single
366 block and the standard says implementations are "encouraged, but not required,"
367 to do so. This implementation provides additional non-standard constructors
368 (selected with the type <code>_Sp_make_shared_tag</code>) which create an
369 object of type <code>_Sp_counted_ptr_inplace</code> to hold the new object.
370 The returned <code>shared_ptr<A></code> needs to know the address of the
371 new <code>A</code> object embedded in the <code>_Sp_counted_ptr_inplace</code>,
372 but it has no way to access it.
373 This implementation uses a "covert channel" to return the address of the
374 embedded object when <code>get_deleter<_Sp_make_shared_tag>()</code>
375 is called. Users should not try to use this.
376 As well as the extra constructors, this implementation also needs some
377 members of _Sp_counted_deleter to be protected where they could otherwise
391 <type>_Sp_counted_base<Lp></type>
393 The base of the hierarchy is parameterized on the lock policy alone.
394 _Sp_counted_base doesn't depend on the type of pointer being managed,
395 it only maintains the reference counts and calls virtual functions when
396 the counts drop to zero. The managed object is destroyed when the last
397 strong reference is dropped, but the _Sp_counted_base itself must exist
398 until the last weak reference is dropped.
403 <type>_Sp_counted_base_impl<Ptr, Deleter, Lp></type>
405 Inherits from _Sp_counted_base and stores a pointer of type <code>Ptr</code>
406 and a deleter of type <code>Deleter</code>. <code>_Sp_deleter</code> is
407 used when the user doesn't supply a custom deleter. Unlike Boost's, this
408 default deleter is not "checked" because GCC already issues a warning if
409 <code>delete</code> is used with an incomplete type.
410 This is the only derived type used by <code>tr1::shared_ptr<Ptr></code>
411 and it is never used by <code>std::shared_ptr</code>, which uses one of
412 the following types, depending on how the shared_ptr is constructed.
417 <sect2 id="shared_ptr.using">
421 <title>Examples</title>
423 Examples of use can be found in the testsuite, under
424 <filename class="directory">testsuite/tr1/2_general_utilities/shared_ptr</filename>.
429 <title>Unresolved Issues</title>
431 The resolution to C++ Standard Library issue <ulink url="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#674">674</ulink>,
432 "shared_ptr interface changes for consistency with N1856" will
433 need to be implemented after it is accepted into the working
434 paper. Issue <ulink url="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#743">743</ulink>
435 might also require changes.
439 The <type>_S_single</type> policy uses atomics when used in MT
440 code, because it uses the same dispatcher functions that check
441 <function>__gthread_active_p()</function>. This could be
442 addressed by providing template specialisations for some members
443 of <classname>_Sp_counted_base<_S_single></classname>.
447 Unlike Boost, this implementation does not use separate classes
448 for the pointer+deleter and pointer+deleter+allocator cases in
449 C++0x mode, combining both into _Sp_counted_deleter and using
450 <classname>allocator</classname> when the user doesn't specify
451 an allocator. If it was found to be beneficial an additional
452 class could easily be added. With the current implementation,
453 the _Sp_counted_deleter and __shared_count constructors taking a
454 custom deleter but no allocator are technically redundant and
455 could be removed, changing callers to always specify an
456 allocator. If a separate pointer+deleter class was added the
457 __shared_count constructor would be needed, so it has been kept
462 The hack used to get the address of the managed object from
463 <function>_Sp_counted_ptr_inplace::_M_get_deleter()</function>
464 is accessible to users. This could be prevented if
465 <function>get_deleter<_Sp_make_shared_tag>()</function>
466 always returned NULL, since the hack only needs to work at a
467 lower level, not in the public API. This wouldn't be difficult,
468 but hasn't been done since there is no danger of accidental
469 misuse: users already know they are relying on unsupported
470 features if they refer to implementation details such as
475 tr1::_Sp_deleter could be a private member of tr1::__shared_count but it
480 Exposing the alias constructor in TR1 mode could simplify the
481 *_pointer_cast functions. Constructor could be private in TR1
482 mode, with the cast functions as friends.
488 <sect2 id="shared_ptr.ack">
489 <title>Acknowledgments</title>
492 The original authors of the Boost shared_ptr, which is really nice
493 code to work with, Peter Dimov in particular for his help and
494 invaluable advice on thread safety. Phillip Jordan and Paolo
495 Carlini for the lock policy implementation.
500 <bibliography id="shared_ptr.biblio">
501 <title>Bibliography</title>
504 <biblioid class="uri">
505 <ulink url="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm">
507 Improving shared_ptr for C++0x, Revision 2
517 <biblioid class="uri">
518 <ulink url="http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html">
520 C++ Standard Library Active Issues List
530 <biblioid class="uri">
531 <ulink url="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf">
533 Working Draft, Standard for Programming Language C++
543 <biblioid class="uri">
544 <ulink url="http://boost.org/libs/smart_ptr/shared_ptr.htm">shared_ptr
546 Boost C++ Libraries documentation, shared_ptr