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>
7 <keyword>ISO C++</keyword>
8 <keyword>shared_ptr</keyword>
15 The shared_ptr class template stores a pointer, usually obtained via new,
16 and implements shared ownership semantics.
19 <section xml:id="shared_ptr.req"><info><title>Requirements</title></info>
26 The standard deliberately doesn't require a reference-counted
27 implementation, allowing other techniques such as a
35 <section xml:id="shared_ptr.design_issues"><info><title>Design Issues</title></info>
40 The <classname>shared_ptr</classname> code is kindly donated to GCC by the Boost
41 project and the original authors of the code. The basic design and
42 algorithms are from Boost, the notes below describe details specific to
43 the GCC implementation. Names have been uglified in this implementation,
44 but the design should be recognisable to anyone familiar with the Boost
49 The basic design is an abstract base class, <code>_Sp_counted_base</code> that
50 does the reference-counting and calls virtual functions when the count
52 Derived classes override those functions to destroy resources in a context
53 where the correct dynamic type is known. This is an application of the
54 technique known as type erasure.
59 <section xml:id="shared_ptr.impl"><info><title>Implementation</title></info>
62 <section xml:id="shared_ptr.hier"><info><title>Class Hierarchy</title></info>
66 A <classname>shared_ptr<T></classname> contains a pointer of
67 type <type>T*</type> and an object of type
68 <classname>__shared_count</classname>. The shared_count contains a
69 pointer of type <type>_Sp_counted_base*</type> which points to the
70 object that maintains the reference-counts and destroys the managed
77 <term><classname>_Sp_counted_base<Lp></classname></term>
80 The base of the hierarchy is parameterized on the lock policy (see below.)
81 _Sp_counted_base doesn't depend on the type of pointer being managed,
82 it only maintains the reference counts and calls virtual functions when
83 the counts drop to zero. The managed object is destroyed when the last
84 strong reference is dropped, but the _Sp_counted_base itself must exist
85 until the last weak reference is dropped.
91 <term><classname>_Sp_counted_base_impl<Ptr, Deleter, Lp></classname></term>
94 Inherits from _Sp_counted_base and stores a pointer of type <code>Ptr</code>
95 and a deleter of type <code>Deleter</code>. <classname>_Sp_deleter</classname> is
96 used when the user doesn't supply a custom deleter. Unlike Boost's, this
97 default deleter is not "checked" because GCC already issues a warning if
98 <function>delete</function> is used with an incomplete type.
99 This is the only derived type used by <classname>tr1::shared_ptr<Ptr></classname>
100 and it is never used by <classname>std::shared_ptr</classname>, which uses one of
101 the following types, depending on how the shared_ptr is constructed.
107 <term><classname>_Sp_counted_ptr<Ptr, Lp></classname></term>
110 Inherits from _Sp_counted_base and stores a pointer of type <type>Ptr</type>,
111 which is passed to <function>delete</function> when the last reference is dropped.
112 This is the simplest form and is used when there is no custom deleter or
119 <term><classname>_Sp_counted_deleter<Ptr, Deleter, Alloc></classname></term>
122 Inherits from _Sp_counted_ptr and adds support for custom deleter and
123 allocator. Empty Base Optimization is used for the allocator. This class
124 is used even when the user only provides a custom deleter, in which case
125 <classname>allocator</classname> is used as the allocator.
131 <term><classname>_Sp_counted_ptr_inplace<Tp, Alloc, Lp></classname></term>
134 Used by <code>allocate_shared</code> and <code>make_shared</code>.
135 Contains aligned storage to hold an object of type <type>Tp</type>,
136 which is constructed in-place with placement <function>new</function>.
137 Has a variadic template constructor allowing any number of arguments to
138 be forwarded to <type>Tp</type>'s constructor.
139 Unlike the other <classname>_Sp_counted_*</classname> classes, this one is parameterized on the
140 type of object, not the type of pointer; this is purely a convenience
141 that simplifies the implementation slightly.
149 C++11-only features are: rvalue-ref/move support, allocator support,
150 aliasing constructor, make_shared & allocate_shared. Additionally,
151 the constructors taking <classname>auto_ptr</classname> parameters are
152 deprecated in C++11 mode.
158 <section xml:id="shared_ptr.thread"><info><title>Thread Safety</title></info>
162 <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety">Thread
163 Safety</link> section of the Boost shared_ptr documentation says "shared_ptr
164 objects offer the same level of thread safety as built-in types."
165 The implementation must ensure that concurrent updates to separate shared_ptr
166 instances are correct even when those instances share a reference count e.g.
170 shared_ptr<A> a(new A);
171 shared_ptr<A> b(a);
173 // Thread 1 // Thread 2
174 a.reset(); b.reset();
178 The dynamically-allocated object must be destroyed by exactly one of the
179 threads. Weak references make things even more interesting.
180 The shared state used to implement shared_ptr must be transparent to the
181 user and invariants must be preserved at all times.
182 The key pieces of shared state are the strong and weak reference counts.
183 Updates to these need to be atomic and visible to all threads to ensure
184 correct cleanup of the managed resource (which is, after all, shared_ptr's
186 On multi-processor systems memory synchronisation may be needed so that
187 reference-count updates and the destruction of the managed resource are
192 The function <function>_Sp_counted_base::_M_add_ref_lock()</function>, called when
193 obtaining a shared_ptr from a weak_ptr, has to test if the managed
194 resource still exists and either increment the reference count or throw
195 <classname>bad_weak_ptr</classname>.
196 In a multi-threaded program there is a potential race condition if the last
197 reference is dropped (and the managed resource destroyed) between testing
198 the reference count and incrementing it, which could result in a shared_ptr
199 pointing to invalid memory.
202 The Boost shared_ptr (as used in GCC) features a clever lock-free
203 algorithm to avoid the race condition, but this relies on the
204 processor supporting an atomic <emphasis>Compare-And-Swap</emphasis>
205 instruction. For other platforms there are fall-backs using mutex
206 locks. Boost (as of version 1.35) includes several different
207 implementations and the preprocessor selects one based on the
208 compiler, standard library, platform etc. For the version of
209 shared_ptr in libstdc++ the compiler and library are fixed, which
210 makes things much simpler: we have an atomic CAS or we don't, see Lock
211 Policy below for details.
216 <section xml:id="shared_ptr.policy"><info><title>Selecting Lock Policy</title></info>
223 There is a single <classname>_Sp_counted_base</classname> class,
224 which is a template parameterized on the enum
225 <type>__gnu_cxx::_Lock_policy</type>. The entire family of classes is
226 parameterized on the lock policy, right up to
227 <classname>__shared_ptr</classname>, <classname>__weak_ptr</classname> and
228 <classname>__enable_shared_from_this</classname>. The actual
229 <classname>std::shared_ptr</classname> class inherits from
230 <classname>__shared_ptr</classname> with the lock policy parameter
231 selected automatically based on the thread model and platform that
232 libstdc++ is configured for, so that the best available template
233 specialization will be used. This design is necessary because it would
234 not be conforming for <classname>shared_ptr</classname> to have an
235 extra template parameter, even if it had a default value. The
236 available policies are:
242 <constant>_S_atomic</constant>
245 Selected when GCC supports a builtin atomic compare-and-swap operation
246 on the target processor (see <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html">Atomic
247 Builtins</link>.) The reference counts are maintained using a lock-free
248 algorithm and GCC's atomic builtins, which provide the required memory
255 <constant>_S_mutex</constant>
258 The _Sp_counted_base specialization for this policy contains a mutex,
259 which is locked in add_ref_lock(). This policy is used when GCC's atomic
260 builtins aren't available so explicit memory barriers are needed in places.
266 <constant>_S_single</constant>
269 This policy uses a non-reentrant add_ref_lock() with no locking. It is
270 used when libstdc++ is built without <literal>--enable-threads</literal>.
276 For all three policies, reference count increments and
277 decrements are done via the functions in
278 <filename>ext/atomicity.h</filename>, which detect if the program
279 is multi-threaded. If only one thread of execution exists in
280 the program then less expensive non-atomic operations are used.
285 <section xml:id="shared_ptr.rel"><info><title>Related functions and classes</title></info>
291 <term><code>dynamic_pointer_cast</code>, <code>static_pointer_cast</code>,
292 <code>const_pointer_cast</code></term>
295 As noted in N2351, these functions can be implemented non-intrusively using
296 the alias constructor. However the aliasing constructor is only available
297 in C++11 mode, so in TR1 mode these casts rely on three non-standard
298 constructors in shared_ptr and __shared_ptr.
299 In C++11 mode these constructors and the related tag types are not needed.
305 <term><code>enable_shared_from_this</code></term>
308 The clever overload to detect a base class of type
309 <code>enable_shared_from_this</code> comes straight from Boost.
310 There is an extra overload for <code>__enable_shared_from_this</code> to
311 work smoothly with <code>__shared_ptr<Tp, Lp></code> using any lock
318 <term><code>make_shared</code>, <code>allocate_shared</code></term>
321 <code>make_shared</code> simply forwards to <code>allocate_shared</code>
322 with <code>std::allocator</code> as the allocator.
323 Although these functions can be implemented non-intrusively using the
324 alias constructor, if they have access to the implementation then it is
325 possible to save storage and reduce the number of heap allocations. The
326 newly constructed object and the _Sp_counted_* can be allocated in a single
327 block and the standard says implementations are "encouraged, but not required,"
328 to do so. This implementation provides additional non-standard constructors
329 (selected with the type <code>_Sp_make_shared_tag</code>) which create an
330 object of type <code>_Sp_counted_ptr_inplace</code> to hold the new object.
331 The returned <code>shared_ptr<A></code> needs to know the address of the
332 new <code>A</code> object embedded in the <code>_Sp_counted_ptr_inplace</code>,
333 but it has no way to access it.
334 This implementation uses a "covert channel" to return the address of the
335 embedded object when <code>get_deleter<_Sp_make_shared_tag>()</code>
336 is called. Users should not try to use this.
337 As well as the extra constructors, this implementation also needs some
338 members of _Sp_counted_deleter to be protected where they could otherwise
350 <section xml:id="shared_ptr.using"><info><title>Use</title></info>
353 <section xml:id="shared_ptr.examples"><info><title>Examples</title></info>
356 Examples of use can be found in the testsuite, under
357 <filename class="directory">testsuite/tr1/2_general_utilities/shared_ptr</filename>,
358 <filename class="directory">testsuite/20_util/shared_ptr</filename>
360 <filename class="directory">testsuite/20_util/weak_ptr</filename>.
364 <section xml:id="shared_ptr.issues"><info><title>Unresolved Issues</title></info>
367 The <emphasis><classname>shared_ptr</classname> atomic access</emphasis>
368 clause in the C++11 standard is not implemented in GCC.
372 Unlike Boost, this implementation does not use separate classes
373 for the pointer+deleter and pointer+deleter+allocator cases in
374 C++11 mode, combining both into _Sp_counted_deleter and using
375 <classname>allocator</classname> when the user doesn't specify
376 an allocator. If it was found to be beneficial an additional
377 class could easily be added. With the current implementation,
378 the _Sp_counted_deleter and __shared_count constructors taking a
379 custom deleter but no allocator are technically redundant and
380 could be removed, changing callers to always specify an
381 allocator. If a separate pointer+deleter class was added the
382 __shared_count constructor would be needed, so it has been kept
387 The hack used to get the address of the managed object from
388 <function>_Sp_counted_ptr_inplace::_M_get_deleter()</function>
389 is accessible to users. This could be prevented if
390 <function>get_deleter<_Sp_make_shared_tag>()</function>
391 always returned NULL, since the hack only needs to work at a
392 lower level, not in the public API. This wouldn't be difficult,
393 but hasn't been done since there is no danger of accidental
394 misuse: users already know they are relying on unsupported
395 features if they refer to implementation details such as
400 tr1::_Sp_deleter could be a private member of tr1::__shared_count but it
408 <section xml:id="shared_ptr.ack"><info><title>Acknowledgments</title></info>
412 The original authors of the Boost shared_ptr, which is really nice
413 code to work with, Peter Dimov in particular for his help and
414 invaluable advice on thread safety. Phillip Jordan and Paolo
415 Carlini for the lock policy implementation.
420 <bibliography xml:id="shared_ptr.biblio"><info><title>Bibliography</title></info>
425 <link xmlns:xlink="http://www.w3.org/1999/xlink"
426 xlink:href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm">
427 Improving shared_ptr for C++0x, Revision 2
438 <link xmlns:xlink="http://www.w3.org/1999/xlink"
439 xlink:href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html">
440 C++ Standard Library Active Issues List
451 <link xmlns:xlink="http://www.w3.org/1999/xlink"
452 xlink:href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf">
453 Working Draft, Standard for Programming Language C++
463 <link xmlns:xlink="http://www.w3.org/1999/xlink"
464 xlink:href="http://www.boost.org/libs/smart_ptr/shared_ptr.htm">
465 Boost C++ Libraries documentation, shared_ptr