]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/libstdc++-v3/contrib/libstdc++-v3-4.7/doc/xml/manual/shared_ptr.xml
update
[l4.git] / l4 / pkg / libstdc++-v3 / contrib / libstdc++-v3-4.7 / 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   </para>
37 </section>
38
39 <section xml:id="shared_ptr.design_issues"><info><title>Design Issues</title></info>
40
41
42
43   <para>
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
49 1.32 shared_ptr.
50   </para>
51
52   <para>
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
55 drops to zero.
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.
59   </para>
60
61 </section>
62
63 <section xml:id="shared_ptr.impl"><info><title>Implementation</title></info>
64
65
66   <section><info><title>Class Hierarchy</title></info>
67     
68
69     <para>
70 A <classname>shared_ptr&lt;T&gt;</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
75 resource.
76     </para>
77
78 <variablelist>
79
80 <varlistentry>
81   <term><classname>_Sp_counted_base&lt;Lp&gt;</classname></term>
82   <listitem>
83     <para>
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.
90     </para>
91   </listitem>
92 </varlistentry>
93
94 <varlistentry>
95   <term><classname>_Sp_counted_base_impl&lt;Ptr, Deleter, Lp&gt;</classname></term>
96   <listitem>
97     <para>
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&lt;Ptr&gt;</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.
106     </para>
107   </listitem>
108 </varlistentry>
109
110 <varlistentry>
111   <term><classname>_Sp_counted_ptr&lt;Ptr, Lp&gt;</classname></term>
112   <listitem>
113     <para>
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
117 allocator.
118     </para>
119   </listitem>
120 </varlistentry>
121
122 <varlistentry>
123   <term><classname>_Sp_counted_deleter&lt;Ptr, Deleter, Alloc&gt;</classname></term>
124   <listitem>
125     <para>
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.
130     </para>
131   </listitem>
132 </varlistentry>
133
134 <varlistentry>
135   <term><classname>_Sp_counted_ptr_inplace&lt;Tp, Alloc, Lp&gt;</classname></term>
136   <listitem>
137     <para>
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.
146     </para>
147   </listitem>
148 </varlistentry>
149
150 </variablelist>
151
152     <para>
153 C++11-only features are: rvalue-ref/move support, allocator support,
154 aliasing constructor, make_shared &amp; allocate_shared. Additionally,
155 the constructors taking <classname>auto_ptr</classname> parameters are
156 deprecated in C++11 mode.
157     </para>
158
159
160   </section>
161
162   <section><info><title>Thread Safety</title></info>
163     
164 <para>
165 The
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.
171 </para>
172
173 <programlisting>
174 shared_ptr&lt;A&gt; a(new A);
175 shared_ptr&lt;A&gt; b(a);
176
177 // Thread 1     // Thread 2
178    a.reset();      b.reset();
179 </programlisting>
180
181 <para>
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
189 job!)
190 On multi-processor systems memory synchronisation may be needed so that
191 reference-count updates and the destruction of the managed resource are
192 race-free.
193 </para>
194
195 <para>
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.
204 </para>
205 <para>
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.
216 </para>
217
218   </section>
219
220   <section><info><title>Selecting Lock Policy</title></info>
221     
222
223     <para>
224     </para>
225
226     <para>
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:
241     </para>
242
243    <orderedlist>
244      <listitem>
245        <para>
246        <constant>_S_Atomic</constant>
247        </para>
248        <para>
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
253 synchronisation.
254        </para>
255      </listitem>
256
257      <listitem>
258        <para>
259        <constant>_S_Mutex</constant>
260        </para>
261        <para>
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.
265        </para>
266      </listitem>
267
268      <listitem>
269        <para>
270        <constant>_S_Single</constant>
271        </para>
272        <para>
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>.
275        </para>
276      </listitem>
277
278    </orderedlist>
279      <para>
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.
285      </para>
286   </section>
287
288
289 <section><info><title>Related functions and classes</title></info>
290
291
292 <variablelist>
293
294 <varlistentry>
295   <term><code>dynamic_pointer_cast</code>, <code>static_pointer_cast</code>,
296 <code>const_pointer_cast</code></term>
297   <listitem>
298     <para>
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.
304     </para>
305   </listitem>
306 </varlistentry>
307
308 <varlistentry>
309   <term><code>enable_shared_from_this</code></term>
310   <listitem>
311     <para>
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&lt;Tp, Lp&gt;</code> using any lock
316 policy.
317     </para>
318   </listitem>
319 </varlistentry>
320
321 <varlistentry>
322   <term><code>make_shared</code>, <code>allocate_shared</code></term>
323   <listitem>
324     <para>
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&lt;A&gt;</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&lt;_Sp_make_shared_tag&gt;()</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
343 be private.
344     </para>
345   </listitem>
346 </varlistentry>
347
348 </variablelist>
349
350 </section>
351
352 </section>
353
354 <section xml:id="shared_ptr.using"><info><title>Use</title></info>
355
356
357   <section><info><title>Examples</title></info>
358     
359     <para>
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>
363       and
364       <filename class="directory">testsuite/20_util/weak_ptr</filename>.
365     </para>
366   </section>
367
368   <section><info><title>Unresolved Issues</title></info>
369     
370     <para>
371       The <emphasis><classname>shared_ptr</classname> atomic access</emphasis>
372       clause in the C++11 standard is not implemented in GCC.
373     </para>
374
375     <para>
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&lt;_S_single&gt;</classname>.
381     </para>
382
383     <para>
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
395       for now.
396     </para>
397
398     <para>
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&lt;_Sp_make_shared_tag&gt;()</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
408       _Sp_make_shared_tag.
409     </para>
410
411     <para>
412       tr1::_Sp_deleter could be a private member of tr1::__shared_count but it
413       would alter the ABI.
414     </para>
415
416   </section>
417
418 </section>
419
420 <section xml:id="shared_ptr.ack"><info><title>Acknowledgments</title></info>
421
422
423   <para>
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.
428   </para>
429
430 </section>
431
432 <bibliography xml:id="shared_ptr.biblio"><info><title>Bibliography</title></info>
433
434
435   <biblioentry>
436       <title>
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
440         </link>
441       </title>
442
443     <subtitle>
444       N2351
445     </subtitle>
446   </biblioentry>
447
448   <biblioentry>
449       <title>
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
453         </link>
454       </title>
455
456     <subtitle>
457       N2456
458     </subtitle>
459   </biblioentry>
460
461   <biblioentry>
462       <title>
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++
466         </link>
467       </title>
468     <subtitle>
469       N2461
470     </subtitle>
471   </biblioentry>
472
473   <biblioentry>
474       <title>
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
478         </link>
479       </title>
480
481     <subtitle>
482       N2461
483     </subtitle>
484   </biblioentry>
485
486 </bibliography>
487
488 </section>