OSDN Git Service

2011-07-29 Benjamin Kosnik <bkoz@redhat.com>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / doc / xml / manual / shared_ptr.xml
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"?>
4
5 <info><title>shared_ptr</title>
6   <keywordset>
7     <keyword>
8       ISO C++
9     </keyword>
10     <keyword>
11       shared_ptr
12     </keyword>
13   </keywordset>
14 </info>
15
16
17
18 <para>
19 The shared_ptr class template stores a pointer, usually obtained via new,
20 and implements shared ownership semantics.
21 </para>
22
23 <section xml:id="shared_ptr.req"><info><title>Requirements</title></info>
24
25
26   <para>
27   </para>
28
29   <para>
30     The standard deliberately doesn't require a reference-counted
31     implementation, allowing other techniques such as a
32     circular-linked-list.
33   </para>
34
35   <para>
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
40     apply.
41   </para>
42
43   <para>
44   </para>
45 </section>
46
47 <section xml:id="shared_ptr.design_issues"><info><title>Design Issues</title></info>
48
49
50
51   <para>
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
57 1.32 shared_ptr.
58   </para>
59
60   <para>
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
63 drops to zero.
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.
67   </para>
68
69 </section>
70
71 <section xml:id="shared_ptr.impl"><info><title>Implementation</title></info>
72
73
74   <section><info><title>Class Hierarchy</title></info>
75     
76
77     <para>
78 A <classname>shared_ptr&lt;T&gt;</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
83 resource.
84     </para>
85
86 <variablelist>
87
88 <varlistentry>
89   <term><classname>_Sp_counted_base&lt;Lp&gt;</classname></term>
90   <listitem>
91     <para>
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.
98     </para>
99   </listitem>
100 </varlistentry>
101
102 <varlistentry>
103   <term><classname>_Sp_counted_base_impl&lt;Ptr, Deleter, Lp&gt;</classname></term>
104   <listitem>
105     <para>
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&lt;Ptr&gt;</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.
114     </para>
115   </listitem>
116 </varlistentry>
117
118 <varlistentry>
119   <term><classname>_Sp_counted_ptr&lt;Ptr, Lp&gt;</classname></term>
120   <listitem>
121     <para>
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
125 allocator.
126     </para>
127   </listitem>
128 </varlistentry>
129
130 <varlistentry>
131   <term><classname>_Sp_counted_deleter&lt;Ptr, Deleter, Alloc&gt;</classname></term>
132   <listitem>
133     <para>
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.
138     </para>
139   </listitem>
140 </varlistentry>
141
142 <varlistentry>
143   <term><classname>_Sp_counted_ptr_inplace&lt;Tp, Alloc, Lp&gt;</classname></term>
144   <listitem>
145     <para>
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.
154     </para>
155   </listitem>
156 </varlistentry>
157
158 </variablelist>
159
160   </section>
161
162   <section><info><title>Thread Safety</title></info>
163     
164
165     <para>
166 C++0x-only features are: rvalue-ref/move support, allocator support,
167 aliasing constructor, make_shared &amp; allocate_shared. Additionally,
168 the constructors taking <classname>auto_ptr</classname> parameters are
169 deprecated in C++0x mode.
170     </para>
171
172 <para>
173 The
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.
179 </para>
180
181 <programlisting>
182 shared_ptr&lt;A&gt; a(new A);
183 shared_ptr&lt;A&gt; b(a);
184
185 // Thread 1     // Thread 2
186    a.reset();      b.reset();
187 </programlisting>
188
189 <para>
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
197 job!)
198 On multi-processor systems memory synchronisation may be needed so that
199 reference-count updates and the destruction of the managed resource are
200 race-free.
201 </para>
202
203 <para>
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.
212 </para>
213 <para>
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.
224 </para>
225
226   </section>
227
228   <section><info><title>Selecting Lock Policy</title></info>
229     
230
231     <para>
232     </para>
233
234     <para>
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:
249     </para>
250
251    <orderedlist>
252      <listitem>
253        <para>
254        <type>_S_Atomic</type>
255        </para>
256        <para>
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
261 synchronisation.
262        </para>
263      </listitem>
264
265      <listitem>
266        <para>
267        <type>_S_Mutex</type>
268        </para>
269        <para>
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.
273        </para>
274      </listitem>
275
276      <listitem>
277        <para>
278        <type>_S_Single</type>
279        </para>
280        <para>
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>.
283        </para>
284      </listitem>
285
286    </orderedlist>
287      <para>
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.
293      </para>
294   </section>
295
296   <section><info><title>Dual C++0x and TR1 Implementation</title></info>
297     
298
299 <para>
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>.
305 </para>
306
307 <para>
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.
312 </para>
313
314 <para>
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
319 the C++0x version.
320 </para>
321 </section>
322
323 <section><info><title>Related functions and classes</title></info>
324
325
326 <variablelist>
327
328 <varlistentry>
329   <term><code>dynamic_pointer_cast</code>, <code>static_pointer_cast</code>,
330 <code>const_pointer_cast</code></term>
331   <listitem>
332     <para>
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.
338     </para>
339   </listitem>
340 </varlistentry>
341
342 <varlistentry>
343   <term><code>enable_shared_from_this</code></term>
344   <listitem>
345     <para>
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&lt;Tp, Lp&gt;</code> using any lock
350 policy.
351     </para>
352   </listitem>
353 </varlistentry>
354
355 <varlistentry>
356   <term><code>make_shared</code>, <code>allocate_shared</code></term>
357   <listitem>
358     <para>
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&lt;A&gt;</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&lt;_Sp_make_shared_tag&gt;()</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
377 be private.
378     </para>
379   </listitem>
380 </varlistentry>
381
382 </variablelist>
383
384 </section>
385
386 </section>
387
388 <!--- XXX
389      <listitem>
390        <type>_Sp_counted_base&lt;Lp&gt;</type>
391        <para>
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.
398        </para>
399      </listitem>
400
401      <listitem>
402        <type>_Sp_counted_base_impl&lt;Ptr, Deleter, Lp&gt;</type>
403        <para>
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&lt;Ptr&gt;</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.
412        </para>
413      </listitem>
414 -->
415
416 <section xml:id="shared_ptr.using"><info><title>Use</title></info>
417
418
419   <section><info><title>Examples</title></info>
420     
421     <para>
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>
425       and
426       <filename class="directory">testsuite/20_util/weak_ptr</filename>.
427     </para>
428   </section>
429
430   <section><info><title>Unresolved Issues</title></info>
431     
432     <para>
433       The <emphasis><classname>shared_ptr</classname> atomic access</emphasis>
434       clause in the C++0x working draft is not implemented in GCC.
435     </para>
436
437     <para>
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&lt;_S_single&gt;</classname>.
443     </para>
444
445     <para>
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
457       for now.
458     </para>
459
460     <para>
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&lt;_Sp_make_shared_tag&gt;()</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
470       _Sp_make_shared_tag.
471     </para>
472
473     <para>
474       tr1::_Sp_deleter could be a private member of tr1::__shared_count but it
475       would alter the ABI.
476     </para>
477
478   </section>
479
480 </section>
481
482 <section xml:id="shared_ptr.ack"><info><title>Acknowledgments</title></info>
483
484
485   <para>
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.
490   </para>
491
492 </section>
493
494 <bibliography xml:id="shared_ptr.biblio"><info><title>Bibliography</title></info>
495
496
497   <biblioentry>
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">
499     </biblioid>
500     <citetitle>
501       Improving shared_ptr for C++0x, Revision 2
502     </citetitle>    
503     <subtitle>
504       N2351
505     </subtitle>
506   </biblioentry>
507
508   <biblioentry>
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">
510     </biblioid>
511     <citetitle>
512       C++ Standard Library Active Issues List
513     </citetitle>
514     <subtitle>
515       N2456
516     </subtitle>
517   </biblioentry>
518
519   <biblioentry>
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">
521     </biblioid>
522     <citetitle>
523       Working Draft, Standard for Programming Language C++
524     </citetitle>
525     <subtitle>
526       N2461
527     </subtitle>
528   </biblioentry>
529
530   <biblioentry>
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
532     </biblioid>
533     <citetitle>
534       Boost C++ Libraries documentation, shared_ptr
535     </citetitle>
536     <subtitle>
537       N2461
538     </subtitle>
539   </biblioentry>
540
541 </bibliography>
542
543 </section>