1 <?xml version="1.0" encoding="ISO-8859-1"?>
3 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
4 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
6 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
8 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
9 <meta name="KEYWORDS" content="HOWTO, libstdc++, GCC, g++, STL" />
10 <meta name="DESCRIPTION" content="Notes on the shared_ptr implementation." />
11 <title>Notes on the shared_ptr implementation.</title>
12 <link rel="StyleSheet" href="../lib3styles.css" type="text/css" />
13 <link rel="Start" href="../documentation.html" type="text/html"
14 title="GNU C++ Standard Library" />
15 <link rel="Bookmark" href="howto.html" type="text/html" title="General Utilities" />
16 <link rel="Copyright" href="../17_intro/license.html" type="text/html" />
17 <link rel="Help" href="../faq/index.html" type="text/html" title="F.A.Q." />
21 Notes on the <code>shared_ptr</code> implementation.
24 prepared by Jonathan Wakely on November 11, 2007
31 The shared_ptr class template stores a pointer, usually obtained via new,
32 and implements shared ownership semantics.
36 2. What the standard says
40 20.6.6.2 - Class template shared_ptr [util.smartptr.shared]
44 The standard deliberately doesn't require a reference-counted implementation,
45 allowing other techniques such as a circular-linked-list.
49 At the time of writing the C++0x working paper doesn't mention how threads
50 affect shared_ptr, but it is likely to follow the existing practice set by
51 <code>boost::shared_ptr</code>. The shared_ptr in libstdc++ is derived
52 from Boost's, so the same rules apply.
56 3. Problems with shared_ptr: TR1 vs C++0x, thread safety.
60 The interface of <code>tr1::shared_ptr</code> was extended for C++0x with
61 support for rvalue-references and the other features from N2351. As
62 with other libstdc++ headers shared by TR1 and C++0x, boost_shared_ptr.h
63 uses conditional compilation, based on the macros _GLIBCXX_INCLUDE_AS_CXX0X
64 and _GLIBCXX_INCLUDE_AS_TR1, to enable and disable features.
68 C++0x-only features are: rvalue-ref/move support, allocator support,
69 aliasing constructor, make_shared & allocate_shared. Additionally, the
70 constructors taking auto_ptr parameters are deprecated in C++0x mode.
75 <a href="http://boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety">Thread
76 Safety</a> section of the Boost shared_ptr documentation says "shared_ptr
77 objects offer the same level of thread safety as built-in types."
78 The implementation must ensure that concurrent updates to separate shared_ptr
79 instances are correct even when those instances share a reference count e.g.
82 shared_ptr<A> a(new A);
83 shared_ptr<A> b(a);
85 // Thread 1 // Thread 2
89 The dynamically-allocated object must be destroyed by exactly one of the
90 threads. Weak references make things even more interesting.
91 The shared state used to implement shared_ptr must be transparent to the
92 user and invariants must be preserved at all times.
93 The key pieces of shared state are the strong and weak reference counts.
94 Updates to these need to be atomic and visible to all threads to ensure
95 correct cleanup of the managed resource (which is, after all, shared_ptr's
97 On multi-processor systems memory synchronisation may be needed so that
98 reference-count updates and the destruction of the managed resource are
103 The function <code>_Sp_counted_base::_M_add_ref_lock()</code>, called when
104 obtaining a shared_ptr from a weak_ptr, has to test if the managed
105 resource still exists and either increment the reference count or throw
106 <code>std::bad_weak_ptr</code>.
107 In a multi-threaded program there is a potential race condition if the last
108 reference is dropped (and the managed resource destroyed) between testing
109 the reference count and incrementing it, which could result in a shared_ptr
110 pointing to invalid memory.
113 The Boost shared_ptr (as used in GCC) features a clever lock-free algorithm
114 to avoid the race condition, but this relies on the processor supporting
115 an atomic <em>Compare-And-Swap</em> instruction. For other platforms there
116 are fall-backs using mutex locks. Boost (as of version 1.35) includes
117 several different implementations and the preprocessor selects one based
118 on the compiler, standard library, platform etc. For the version of
119 shared_ptr in libstdc++ the compiler and library are fixed, which makes
120 things much simpler: we have an atomic CAS or we don't, see Lock Policy
125 4. Design and Implementation Details
129 The shared_ptr code in libstdc++ was kindly donated to GCC by the Boost
130 project and the original authors of the code. The basic design and
131 algorithms are from Boost, the notes below describe details specific to
132 the GCC implementation. Names have been uglified in this implementation,
133 but the design should be recognisable to anyone familiar with the Boost
138 The basic design is an abstract base class, <code>_Sp_counted_base</code> that
139 does the reference-counting and calls virtual functions when the count
141 Derived classes override those functions to destroy resources in a context
142 where the correct dynamic type is known. This is an application of the
143 technique known as type erasure.
147 C++0x and TR1 Implementations
151 The classes derived from <code>_Sp_counted_base</code> (see Class Hierarchy
152 below) and <code>__shared_count</code> are implemented separately for C++0x
153 and TR1, in <tt>bits/boost_sp_shared_count.h</tt> and
154 <tt>tr1/boost_sp_shared_count.h</tt> respectively. All other classes
155 including <code>_Sp_counted_base</code> are shared by both implementations.
159 The TR1 implementation is considered relatively stable, so is unlikely to
160 change unless bug fixes require it to. If the code that is common to both
161 C++0x and TR1 modes needs to diverge further then it might be necessary to
162 duplicate additional classes and only make changes to the C++0x versions.
170 Libstdc++ has a single <code>_Sp_counted_base</code> class, which is a
171 template parameterized on the enum <code>__gnu_cxx::_Lock_policy</code>.
172 The entire family of classes is parameterized on the lock policy, right up
173 to <code>__shared_ptr</code>, <code>__weak_ptr</code> and
174 <code>__enable_shared_from_this</code>. The actual
175 <code>std::shared_ptr</code> class inherits from <code>__shared_ptr</code>
176 with the lock policy parameter selected automatically based on the thread
177 model and platform that libstdc++ is configured for, so that the best
178 available template specialization will be used. This design is necessary
179 because it would not be conforming for <code>std::shared_ptr</code> to have
180 an extra template parameter, even if it had a default value.
181 The available policies are:
185 <dt><code>_S_Atomic</code></dt>
187 Selected when GCC supports a builtin atomic compare-and-swap
188 operation on the target processor (see
189 <a href="http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html">Atomic
191 The reference counts are maintained using a lock-free algorithm and GCC's
192 atomic builtins, which provide the required memory synchronisation.
194 <dt><code>_S_Mutex</code></dt>
196 The _Sp_counted_base specialization for this policy contains a mutex,
197 which is locked in add_ref_lock(). This policy is used when GCC's atomic
198 builtins aren't available so explicit memory barriers are needed in places.
200 <dt><code>_S_Single</code></dt>
202 This policy uses a non-reentrant add_ref_lock() with no locking. It is
203 used when libstdc++ is built without <em>--enable-threads</em>.
208 For all three policies, reference count increments and decrements are done
209 via the functions in <tt><ext/atomicity.h></tt>, which detect if the
210 program is multi-threaded.
211 If only one thread of execution exists in the program then less expensive
212 non-atomic operations are used.
220 A <code>shared_ptr<T></code> contains a pointer of type <code>T*</code>
221 and an object of type <code>__shared_count</code>. The shared_count contains
222 a pointer of type <code>_Sp_counted_base*</code> which points to the object
223 that maintains the reference-counts and destroys the managed resource.
227 <dt><code>_Sp_counted_base<Lp></code></dt>
229 The base of the hierarchy is parameterized on the lock policy alone.
230 _Sp_counted_base doesn't depend on the type of pointer being managed,
231 it only maintains the reference counts and calls virtual functions when
232 the counts drop to zero. The managed object is destroyed when the last
233 strong reference is dropped, but the _Sp_counted_base itself must exist
234 until the last weak reference is dropped.
236 <dt><code>_Sp_counted_base_impl<Ptr, Deleter, Lp></code></dt>
238 Inherits from _Sp_counted_base and stores a pointer of type <code>Ptr</code>
239 and a deleter of type <code>Deleter</code>. <code>_Sp_deleter</code> is
240 used when the user doesn't supply a custom deleter. Unlike Boost's, this
241 default deleter is not "checked" because GCC already issues a warning if
242 <code>delete</code> is used with an incomplete type.
243 This is the only derived type used by <code>tr1::shared_ptr<Ptr></code>
244 and it is never used by <code>std::shared_ptr</code>, which uses one of
245 the following types, depending on how the shared_ptr is constructed.
247 <dt><code>_Sp_counted_ptr<Ptr, Lp></code></dt>
249 Inherits from _Sp_counted_base and stores a pointer of type <code>Ptr</code>,
250 which is passed to <code>delete</code> when the last reference is dropped.
251 This is the simplest form and is used when there is no custom deleter or
254 <dt><code>_Sp_counted_deleter<Ptr, Deleter, Alloc></code></dt>
256 Inherits from _Sp_counted_ptr and adds support for custom deleter and
257 allocator. Empty Base Optimization is used for the allocator. This class
258 is used even when the user only provides a custom deleter, in which case
259 <code>std::allocator</code> is used as the allocator.
261 <dt><code>_Sp_counted_ptr_inplace<Tp, Alloc, Lp></code></dt>
263 Used by <code>allocate_shared</code> and <code>make_shared</code>.
264 Contains aligned storage to hold an object of type <code>Tp</code>,
265 which is constructed in-place with placement <code>new</code>.
266 Has a variadic template constructor allowing any number of arguments to
267 be forwarded to <code>Tp</code>'s constructor.
268 Unlike the other _Sp_counted_* classes, this one is parameterized on the
269 type of object, not the type of pointer; this is purely a convenience
270 that simplifies the implementation slightly.
275 Related functions and classes
279 <dt><code>dynamic_pointer_cast</code>, <code>static_pointer_cast</code>,
280 <code>const_pointer_cast</code></dt>
282 As noted in N2351, these functions can be implemented non-intrusively using
283 the alias constructor. However the aliasing constructor is only available
284 in C++0x mode, so in TR1 mode these casts rely on three non-standard
285 constructors in shared_ptr and __shared_ptr.
286 In C++0x mode these constructors and the related tag types are not needed.
288 <dt><code>enable_shared_from_this</code></dt>
290 The clever overload to detect a base class of type
291 <code>enable_shared_from_this</code> comes straight from Boost.
292 There is an extra overload for <code>__enable_shared_from_this</code> to
293 work smoothly with <code>__shared_ptr<Tp, Lp></code> using any lock
296 <dt><code>make_shared</code>, <code>allocate_shared</code></dt>
298 <code>make_shared</code> simply forwards to <code>allocate_shared</code>
299 with <code>std::allocator</code> as the allocator.
300 Although these functions can be implemented non-intrusively using the
301 alias constructor, if they have access to the implementation then it is
302 possible to save storage and reduce the number of heap allocations. The
303 newly constructed object and the _Sp_counted_* can be allocated in a single
304 block and the standard says implementations are "encouraged, but not required,"
305 to do so. This implementation provides additional non-standard constructors
306 (selected with the type <code>_Sp_make_shared_tag</code>) which create an
307 object of type <code>_Sp_counted_ptr_inplace</code> to hold the new object.
308 The returned <code>shared_ptr<A></code> needs to know the address of the
309 new <code>A</code> object embedded in the <code>_Sp_counted_ptr_inplace</code>,
310 but it has no way to access it.
311 This implementation uses a "covert channel" to return the address of the
312 embedded object when <code>get_deleter<_Sp_make_shared_tag>()</code>
313 is called. Users should not try to use this.
314 As well as the extra constructors, this implementation also needs some
315 members of _Sp_counted_deleter to be protected where they could otherwise
325 Examples of use can be found in the testsuite, under
326 <tt>testsuite/tr1/2_general_utilities/shared_ptr</tt>.
334 The resolution to C++ Standard Library issue <a
335 href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#674">674</a>,
336 "shared_ptr interface changes for consistency with N1856" will need to be
337 implemented after it is accepted into the working paper. Issue <a
338 href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#743">743</a>
339 might also require changes.
343 The _S_single policy uses atomics when used in MT code, because it uses
344 the same dispatcher functions that check __gthread_active_p(). This could be
345 addressed by providing template specialisations for some members of
346 _Sp_counted_base<_S_single>.
350 Unlike Boost, this implementation does not use separate classes for the
351 pointer+deleter and pointer+deleter+allocator cases in C++0x mode, combining
352 both into _Sp_counted_deleter and using std::allocator when the user doesn't
353 specify an allocator.
354 If it was found to be beneficial an additional class could easily be added.
355 With the current implementation, the _Sp_counted_deleter and __shared_count
356 constructors taking a custom deleter but no allocator are technically
357 redundant and could be removed, changing callers to always specify an
358 allocator. If a separate pointer+deleter class was added the __shared_count
359 constructor would be needed, so it has been kept for now.
363 The hack used to get the address of the managed object from
364 _Sp_counted_ptr_inplace::_M_get_deleter() is accessible to users. This
365 could be prevented if get_deleter<_Sp_make_shared_tag>() always
366 returned NULL, since the hack only needs to work at a lower level, not
367 in the public API. This wouldn't be difficult, but hasn't been done since
368 there is no danger of accidental misuse: users already know they are
369 relying on unsupported features if they refer to implementation details
370 such as _Sp_make_shared_tag.
374 tr1::_Sp_deleter could be a private member of tr1::__shared_count but it
379 Exposing the alias constructor in TR1 mode could simplify the *_pointer_cast
381 Constructor could be private in TR1 mode, with the cast functions as friends.
388 The original authors of the Boost shared_ptr, which is really nice code
389 to work with, Peter Dimov in particular for his help and invaluable advice
391 Phillip Jordan and Paolo Carlini for the lock policy implementation.
396 8. Bibliography / Referenced Documents
400 N2351 Improving shared_ptr for C++0x, Revision 2
401 <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm</a>
405 N2456 C++ Standard Library Active Issues List (Revision R52)
406 <a href="http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html">http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html</a></p>
408 N2461 Working Draft, Standard for Programming Language C++
409 <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf</a>
413 Boost C++ Libraries documentation - shared_ptr class template
414 <a href="http://boost.org/libs/smart_ptr/shared_ptr.htm">http://boost.org/libs/smart_ptr/shared_ptr.htm</a>