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
39 <section xml:id="shared_ptr.design_issues"><info><title>Design Issues</title></info>
44 The <classname>shared_ptr</classname> code is kindly donated to GCC by the Boost
45 project and the original authors of the code. The basic design and
46 algorithms are from Boost, the notes below describe details specific to
47 the GCC implementation. Names have been uglified in this implementation,
48 but the design should be recognisable to anyone familiar with the Boost
53 The basic design is an abstract base class, <code>_Sp_counted_base</code> that
54 does the reference-counting and calls virtual functions when the count
56 Derived classes override those functions to destroy resources in a context
57 where the correct dynamic type is known. This is an application of the
58 technique known as type erasure.
63 <section xml:id="shared_ptr.impl"><info><title>Implementation</title></info>
66 <section><info><title>Class Hierarchy</title></info>
70 A <classname>shared_ptr<T></classname> contains a pointer of
71 type <type>T*</type> and an object of type
72 <classname>__shared_count</classname>. The shared_count contains a
73 pointer of type <type>_Sp_counted_base*</type> which points to the
74 object that maintains the reference-counts and destroys the managed
81 <term><classname>_Sp_counted_base<Lp></classname></term>
84 The base of the hierarchy is parameterized on the lock policy (see below.)
85 _Sp_counted_base doesn't depend on the type of pointer being managed,
86 it only maintains the reference counts and calls virtual functions when
87 the counts drop to zero. The managed object is destroyed when the last
88 strong reference is dropped, but the _Sp_counted_base itself must exist
89 until the last weak reference is dropped.
95 <term><classname>_Sp_counted_base_impl<Ptr, Deleter, Lp></classname></term>
98 Inherits from _Sp_counted_base and stores a pointer of type <code>Ptr</code>
99 and a deleter of type <code>Deleter</code>. <classname>_Sp_deleter</classname> is
100 used when the user doesn't supply a custom deleter. Unlike Boost's, this
101 default deleter is not "checked" because GCC already issues a warning if
102 <function>delete</function> is used with an incomplete type.
103 This is the only derived type used by <classname>tr1::shared_ptr<Ptr></classname>
104 and it is never used by <classname>std::shared_ptr</classname>, which uses one of
105 the following types, depending on how the shared_ptr is constructed.
111 <term><classname>_Sp_counted_ptr<Ptr, Lp></classname></term>
114 Inherits from _Sp_counted_base and stores a pointer of type <type>Ptr</type>,
115 which is passed to <function>delete</function> when the last reference is dropped.
116 This is the simplest form and is used when there is no custom deleter or
123 <term><classname>_Sp_counted_deleter<Ptr, Deleter, Alloc></classname></term>
126 Inherits from _Sp_counted_ptr and adds support for custom deleter and
127 allocator. Empty Base Optimization is used for the allocator. This class
128 is used even when the user only provides a custom deleter, in which case
129 <classname>allocator</classname> is used as the allocator.
135 <term><classname>_Sp_counted_ptr_inplace<Tp, Alloc, Lp></classname></term>
138 Used by <code>allocate_shared</code> and <code>make_shared</code>.
139 Contains aligned storage to hold an object of type <type>Tp</type>,
140 which is constructed in-place with placement <function>new</function>.
141 Has a variadic template constructor allowing any number of arguments to
142 be forwarded to <type>Tp</type>'s constructor.
143 Unlike the other <classname>_Sp_counted_*</classname> classes, this one is parameterized on the
144 type of object, not the type of pointer; this is purely a convenience
145 that simplifies the implementation slightly.
153 C++11-only features are: rvalue-ref/move support, allocator support,
154 aliasing constructor, make_shared & allocate_shared. Additionally,
155 the constructors taking <classname>auto_ptr</classname> parameters are
156 deprecated in C++11 mode.
162 <section><info><title>Thread Safety</title></info>
166 <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety">Thread
167 Safety</link> section of the Boost shared_ptr documentation says "shared_ptr
168 objects offer the same level of thread safety as built-in types."
169 The implementation must ensure that concurrent updates to separate shared_ptr
170 instances are correct even when those instances share a reference count e.g.
174 shared_ptr<A> a(new A);
175 shared_ptr<A> b(a);
177 // Thread 1 // Thread 2
178 a.reset(); b.reset();
182 The dynamically-allocated object must be destroyed by exactly one of the
183 threads. Weak references make things even more interesting.
184 The shared state used to implement shared_ptr must be transparent to the
185 user and invariants must be preserved at all times.
186 The key pieces of shared state are the strong and weak reference counts.
187 Updates to these need to be atomic and visible to all threads to ensure
188 correct cleanup of the managed resource (which is, after all, shared_ptr's
190 On multi-processor systems memory synchronisation may be needed so that
191 reference-count updates and the destruction of the managed resource are
196 The function <function>_Sp_counted_base::_M_add_ref_lock()</function>, called when
197 obtaining a shared_ptr from a weak_ptr, has to test if the managed
198 resource still exists and either increment the reference count or throw
199 <classname>bad_weak_ptr</classname>.
200 In a multi-threaded program there is a potential race condition if the last
201 reference is dropped (and the managed resource destroyed) between testing
202 the reference count and incrementing it, which could result in a shared_ptr
203 pointing to invalid memory.
206 The Boost shared_ptr (as used in GCC) features a clever lock-free
207 algorithm to avoid the race condition, but this relies on the
208 processor supporting an atomic <emphasis>Compare-And-Swap</emphasis>
209 instruction. For other platforms there are fall-backs using mutex
210 locks. Boost (as of version 1.35) includes several different
211 implementations and the preprocessor selects one based on the
212 compiler, standard library, platform etc. For the version of
213 shared_ptr in libstdc++ the compiler and library are fixed, which
214 makes things much simpler: we have an atomic CAS or we don't, see Lock
215 Policy below for details.
220 <section><info><title>Selecting Lock Policy</title></info>
227 There is a single <classname>_Sp_counted_base</classname> class,
228 which is a template parameterized on the enum
229 <type>__gnu_cxx::_Lock_policy</type>. The entire family of classes is
230 parameterized on the lock policy, right up to
231 <classname>__shared_ptr</classname>, <classname>__weak_ptr</classname> and
232 <classname>__enable_shared_from_this</classname>. The actual
233 <classname>std::shared_ptr</classname> class inherits from
234 <classname>__shared_ptr</classname> with the lock policy parameter
235 selected automatically based on the thread model and platform that
236 libstdc++ is configured for, so that the best available template
237 specialization will be used. This design is necessary because it would
238 not be conforming for <classname>shared_ptr</classname> to have an
239 extra template parameter, even if it had a default value. The
240 available policies are:
246 <constant>_S_Atomic</constant>
249 Selected when GCC supports a builtin atomic compare-and-swap operation
250 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
251 Builtins</link>.) The reference counts are maintained using a lock-free
252 algorithm and GCC's atomic builtins, which provide the required memory
259 <constant>_S_Mutex</constant>
262 The _Sp_counted_base specialization for this policy contains a mutex,
263 which is locked in add_ref_lock(). This policy is used when GCC's atomic
264 builtins aren't available so explicit memory barriers are needed in places.
270 <constant>_S_Single</constant>
273 This policy uses a non-reentrant add_ref_lock() with no locking. It is
274 used when libstdc++ is built without <literal>--enable-threads</literal>.
280 For all three policies, reference count increments and
281 decrements are done via the functions in
282 <filename>ext/atomicity.h</filename>, which detect if the program
283 is multi-threaded. If only one thread of execution exists in
284 the program then less expensive non-atomic operations are used.
289 <section><info><title>Related functions and classes</title></info>
295 <term><code>dynamic_pointer_cast</code>, <code>static_pointer_cast</code>,
296 <code>const_pointer_cast</code></term>
299 As noted in N2351, these functions can be implemented non-intrusively using
300 the alias constructor. However the aliasing constructor is only available
301 in C++11 mode, so in TR1 mode these casts rely on three non-standard
302 constructors in shared_ptr and __shared_ptr.
303 In C++11 mode these constructors and the related tag types are not needed.
309 <term><code>enable_shared_from_this</code></term>
312 The clever overload to detect a base class of type
313 <code>enable_shared_from_this</code> comes straight from Boost.
314 There is an extra overload for <code>__enable_shared_from_this</code> to
315 work smoothly with <code>__shared_ptr<Tp, Lp></code> using any lock
322 <term><code>make_shared</code>, <code>allocate_shared</code></term>
325 <code>make_shared</code> simply forwards to <code>allocate_shared</code>
326 with <code>std::allocator</code> as the allocator.
327 Although these functions can be implemented non-intrusively using the
328 alias constructor, if they have access to the implementation then it is
329 possible to save storage and reduce the number of heap allocations. The
330 newly constructed object and the _Sp_counted_* can be allocated in a single
331 block and the standard says implementations are "encouraged, but not required,"
332 to do so. This implementation provides additional non-standard constructors
333 (selected with the type <code>_Sp_make_shared_tag</code>) which create an
334 object of type <code>_Sp_counted_ptr_inplace</code> to hold the new object.
335 The returned <code>shared_ptr<A></code> needs to know the address of the
336 new <code>A</code> object embedded in the <code>_Sp_counted_ptr_inplace</code>,
337 but it has no way to access it.
338 This implementation uses a "covert channel" to return the address of the
339 embedded object when <code>get_deleter<_Sp_make_shared_tag>()</code>
340 is called. Users should not try to use this.
341 As well as the extra constructors, this implementation also needs some
342 members of _Sp_counted_deleter to be protected where they could otherwise
354 <section xml:id="shared_ptr.using"><info><title>Use</title></info>
357 <section><info><title>Examples</title></info>
360 Examples of use can be found in the testsuite, under
361 <filename class="directory">testsuite/tr1/2_general_utilities/shared_ptr</filename>,
362 <filename class="directory">testsuite/20_util/shared_ptr</filename>
364 <filename class="directory">testsuite/20_util/weak_ptr</filename>.
368 <section><info><title>Unresolved Issues</title></info>
371 The <emphasis><classname>shared_ptr</classname> atomic access</emphasis>
372 clause in the C++11 standard is not implemented in GCC.
376 The <type>_S_single</type> policy uses atomics when used in MT
377 code, because it uses the same dispatcher functions that check
378 <function>__gthread_active_p()</function>. This could be
379 addressed by providing template specialisations for some members
380 of <classname>_Sp_counted_base<_S_single></classname>.
384 Unlike Boost, this implementation does not use separate classes
385 for the pointer+deleter and pointer+deleter+allocator cases in
386 C++11 mode, combining both into _Sp_counted_deleter and using
387 <classname>allocator</classname> when the user doesn't specify
388 an allocator. If it was found to be beneficial an additional
389 class could easily be added. With the current implementation,
390 the _Sp_counted_deleter and __shared_count constructors taking a
391 custom deleter but no allocator are technically redundant and
392 could be removed, changing callers to always specify an
393 allocator. If a separate pointer+deleter class was added the
394 __shared_count constructor would be needed, so it has been kept
399 The hack used to get the address of the managed object from
400 <function>_Sp_counted_ptr_inplace::_M_get_deleter()</function>
401 is accessible to users. This could be prevented if
402 <function>get_deleter<_Sp_make_shared_tag>()</function>
403 always returned NULL, since the hack only needs to work at a
404 lower level, not in the public API. This wouldn't be difficult,
405 but hasn't been done since there is no danger of accidental
406 misuse: users already know they are relying on unsupported
407 features if they refer to implementation details such as
412 tr1::_Sp_deleter could be a private member of tr1::__shared_count but it
420 <section xml:id="shared_ptr.ack"><info><title>Acknowledgments</title></info>
424 The original authors of the Boost shared_ptr, which is really nice
425 code to work with, Peter Dimov in particular for his help and
426 invaluable advice on thread safety. Phillip Jordan and Paolo
427 Carlini for the lock policy implementation.
432 <bibliography xml:id="shared_ptr.biblio"><info><title>Bibliography</title></info>
437 <link xmlns:xlink="http://www.w3.org/1999/xlink"
438 xlink:href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm">
439 Improving shared_ptr for C++0x, Revision 2
450 <link xmlns:xlink="http://www.w3.org/1999/xlink"
451 xlink:href="http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html">
452 C++ Standard Library Active Issues List
463 <link xmlns:xlink="http://www.w3.org/1999/xlink"
464 xlink:href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf">
465 Working Draft, Standard for Programming Language C++
475 <link xmlns:xlink="http://www.w3.org/1999/xlink"
476 xlink:href="http://boost.org/libs/smart_ptr/shared_ptr.htm">
477 Boost C++ Libraries documentation, shared_ptr