shared_ptr.xml revision 1.1.1.1.8.1
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>ISO C++</keyword> 8 <keyword>shared_ptr</keyword> 9 </keywordset> 10</info> 11 12 13 14<para> 15The shared_ptr class template stores a pointer, usually obtained via new, 16and implements shared ownership semantics. 17</para> 18 19<section xml:id="shared_ptr.req"><info><title>Requirements</title></info> 20 21 22 <para> 23 </para> 24 25 <para> 26 The standard deliberately doesn't require a reference-counted 27 implementation, allowing other techniques such as a 28 circular-linked-list. 29 </para> 30 31 <para> 32 </para> 33</section> 34 35<section xml:id="shared_ptr.design_issues"><info><title>Design Issues</title></info> 36 37 38 39 <para> 40The <classname>shared_ptr</classname> code is kindly donated to GCC by the Boost 41project and the original authors of the code. The basic design and 42algorithms are from Boost, the notes below describe details specific to 43the GCC implementation. Names have been uglified in this implementation, 44but the design should be recognisable to anyone familiar with the Boost 451.32 shared_ptr. 46 </para> 47 48 <para> 49The basic design is an abstract base class, <code>_Sp_counted_base</code> that 50does the reference-counting and calls virtual functions when the count 51drops to zero. 52Derived classes override those functions to destroy resources in a context 53where the correct dynamic type is known. This is an application of the 54technique known as type erasure. 55 </para> 56 57</section> 58 59<section xml:id="shared_ptr.impl"><info><title>Implementation</title></info> 60 61 62 <section><info><title>Class Hierarchy</title></info> 63 64 65 <para> 66A <classname>shared_ptr<T></classname> contains a pointer of 67type <type>T*</type> and an object of type 68<classname>__shared_count</classname>. The shared_count contains a 69pointer of type <type>_Sp_counted_base*</type> which points to the 70object that maintains the reference-counts and destroys the managed 71resource. 72 </para> 73 74<variablelist> 75 76<varlistentry> 77 <term><classname>_Sp_counted_base<Lp></classname></term> 78 <listitem> 79 <para> 80The 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, 82it only maintains the reference counts and calls virtual functions when 83the counts drop to zero. The managed object is destroyed when the last 84strong reference is dropped, but the _Sp_counted_base itself must exist 85until the last weak reference is dropped. 86 </para> 87 </listitem> 88</varlistentry> 89 90<varlistentry> 91 <term><classname>_Sp_counted_base_impl<Ptr, Deleter, Lp></classname></term> 92 <listitem> 93 <para> 94Inherits from _Sp_counted_base and stores a pointer of type <code>Ptr</code> 95and a deleter of type <code>Deleter</code>. <classname>_Sp_deleter</classname> is 96used when the user doesn't supply a custom deleter. Unlike Boost's, this 97default deleter is not "checked" because GCC already issues a warning if 98<function>delete</function> is used with an incomplete type. 99This is the only derived type used by <classname>tr1::shared_ptr<Ptr></classname> 100and it is never used by <classname>std::shared_ptr</classname>, which uses one of 101the following types, depending on how the shared_ptr is constructed. 102 </para> 103 </listitem> 104</varlistentry> 105 106<varlistentry> 107 <term><classname>_Sp_counted_ptr<Ptr, Lp></classname></term> 108 <listitem> 109 <para> 110Inherits from _Sp_counted_base and stores a pointer of type <type>Ptr</type>, 111which is passed to <function>delete</function> when the last reference is dropped. 112This is the simplest form and is used when there is no custom deleter or 113allocator. 114 </para> 115 </listitem> 116</varlistentry> 117 118<varlistentry> 119 <term><classname>_Sp_counted_deleter<Ptr, Deleter, Alloc></classname></term> 120 <listitem> 121 <para> 122Inherits from _Sp_counted_ptr and adds support for custom deleter and 123allocator. Empty Base Optimization is used for the allocator. This class 124is used even when the user only provides a custom deleter, in which case 125<classname>allocator</classname> is used as the allocator. 126 </para> 127 </listitem> 128</varlistentry> 129 130<varlistentry> 131 <term><classname>_Sp_counted_ptr_inplace<Tp, Alloc, Lp></classname></term> 132 <listitem> 133 <para> 134Used by <code>allocate_shared</code> and <code>make_shared</code>. 135Contains aligned storage to hold an object of type <type>Tp</type>, 136which is constructed in-place with placement <function>new</function>. 137Has a variadic template constructor allowing any number of arguments to 138be forwarded to <type>Tp</type>'s constructor. 139Unlike the other <classname>_Sp_counted_*</classname> classes, this one is parameterized on the 140type of object, not the type of pointer; this is purely a convenience 141that simplifies the implementation slightly. 142 </para> 143 </listitem> 144</varlistentry> 145 146</variablelist> 147 148 <para> 149C++11-only features are: rvalue-ref/move support, allocator support, 150aliasing constructor, make_shared & allocate_shared. Additionally, 151the constructors taking <classname>auto_ptr</classname> parameters are 152deprecated in C++11 mode. 153 </para> 154 155 156 </section> 157 158 <section><info><title>Thread Safety</title></info> 159 160<para> 161The 162<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety">Thread 163Safety</link> section of the Boost shared_ptr documentation says "shared_ptr 164objects offer the same level of thread safety as built-in types." 165The implementation must ensure that concurrent updates to separate shared_ptr 166instances are correct even when those instances share a reference count e.g. 167</para> 168 169<programlisting> 170shared_ptr<A> a(new A); 171shared_ptr<A> b(a); 172 173// Thread 1 // Thread 2 174 a.reset(); b.reset(); 175</programlisting> 176 177<para> 178The dynamically-allocated object must be destroyed by exactly one of the 179threads. Weak references make things even more interesting. 180The shared state used to implement shared_ptr must be transparent to the 181user and invariants must be preserved at all times. 182The key pieces of shared state are the strong and weak reference counts. 183Updates to these need to be atomic and visible to all threads to ensure 184correct cleanup of the managed resource (which is, after all, shared_ptr's 185job!) 186On multi-processor systems memory synchronisation may be needed so that 187reference-count updates and the destruction of the managed resource are 188race-free. 189</para> 190 191<para> 192The function <function>_Sp_counted_base::_M_add_ref_lock()</function>, called when 193obtaining a shared_ptr from a weak_ptr, has to test if the managed 194resource still exists and either increment the reference count or throw 195<classname>bad_weak_ptr</classname>. 196In a multi-threaded program there is a potential race condition if the last 197reference is dropped (and the managed resource destroyed) between testing 198the reference count and incrementing it, which could result in a shared_ptr 199pointing to invalid memory. 200</para> 201<para> 202The Boost shared_ptr (as used in GCC) features a clever lock-free 203algorithm to avoid the race condition, but this relies on the 204processor supporting an atomic <emphasis>Compare-And-Swap</emphasis> 205instruction. For other platforms there are fall-backs using mutex 206locks. Boost (as of version 1.35) includes several different 207implementations and the preprocessor selects one based on the 208compiler, standard library, platform etc. For the version of 209shared_ptr in libstdc++ the compiler and library are fixed, which 210makes things much simpler: we have an atomic CAS or we don't, see Lock 211Policy below for details. 212</para> 213 214 </section> 215 216 <section><info><title>Selecting Lock Policy</title></info> 217 218 219 <para> 220 </para> 221 222 <para> 223There is a single <classname>_Sp_counted_base</classname> class, 224which is a template parameterized on the enum 225<type>__gnu_cxx::_Lock_policy</type>. The entire family of classes is 226parameterized 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 231selected automatically based on the thread model and platform that 232libstdc++ is configured for, so that the best available template 233specialization will be used. This design is necessary because it would 234not be conforming for <classname>shared_ptr</classname> to have an 235extra template parameter, even if it had a default value. The 236available policies are: 237 </para> 238 239 <orderedlist> 240 <listitem> 241 <para> 242 <constant>_S_Atomic</constant> 243 </para> 244 <para> 245Selected when GCC supports a builtin atomic compare-and-swap operation 246on 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 247Builtins</link>.) The reference counts are maintained using a lock-free 248algorithm and GCC's atomic builtins, which provide the required memory 249synchronisation. 250 </para> 251 </listitem> 252 253 <listitem> 254 <para> 255 <constant>_S_Mutex</constant> 256 </para> 257 <para> 258The _Sp_counted_base specialization for this policy contains a mutex, 259which is locked in add_ref_lock(). This policy is used when GCC's atomic 260builtins aren't available so explicit memory barriers are needed in places. 261 </para> 262 </listitem> 263 264 <listitem> 265 <para> 266 <constant>_S_Single</constant> 267 </para> 268 <para> 269This policy uses a non-reentrant add_ref_lock() with no locking. It is 270used when libstdc++ is built without <literal>--enable-threads</literal>. 271 </para> 272 </listitem> 273 274 </orderedlist> 275 <para> 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. 281 </para> 282 </section> 283 284 285<section><info><title>Related functions and classes</title></info> 286 287 288<variablelist> 289 290<varlistentry> 291 <term><code>dynamic_pointer_cast</code>, <code>static_pointer_cast</code>, 292<code>const_pointer_cast</code></term> 293 <listitem> 294 <para> 295As noted in N2351, these functions can be implemented non-intrusively using 296the alias constructor. However the aliasing constructor is only available 297in C++11 mode, so in TR1 mode these casts rely on three non-standard 298constructors in shared_ptr and __shared_ptr. 299In C++11 mode these constructors and the related tag types are not needed. 300 </para> 301 </listitem> 302</varlistentry> 303 304<varlistentry> 305 <term><code>enable_shared_from_this</code></term> 306 <listitem> 307 <para> 308The clever overload to detect a base class of type 309<code>enable_shared_from_this</code> comes straight from Boost. 310There is an extra overload for <code>__enable_shared_from_this</code> to 311work smoothly with <code>__shared_ptr<Tp, Lp></code> using any lock 312policy. 313 </para> 314 </listitem> 315</varlistentry> 316 317<varlistentry> 318 <term><code>make_shared</code>, <code>allocate_shared</code></term> 319 <listitem> 320 <para> 321<code>make_shared</code> simply forwards to <code>allocate_shared</code> 322with <code>std::allocator</code> as the allocator. 323Although these functions can be implemented non-intrusively using the 324alias constructor, if they have access to the implementation then it is 325possible to save storage and reduce the number of heap allocations. The 326newly constructed object and the _Sp_counted_* can be allocated in a single 327block and the standard says implementations are "encouraged, but not required," 328to do so. This implementation provides additional non-standard constructors 329(selected with the type <code>_Sp_make_shared_tag</code>) which create an 330object of type <code>_Sp_counted_ptr_inplace</code> to hold the new object. 331The returned <code>shared_ptr<A></code> needs to know the address of the 332new <code>A</code> object embedded in the <code>_Sp_counted_ptr_inplace</code>, 333but it has no way to access it. 334This implementation uses a "covert channel" to return the address of the 335embedded object when <code>get_deleter<_Sp_make_shared_tag>()</code> 336is called. Users should not try to use this. 337As well as the extra constructors, this implementation also needs some 338members of _Sp_counted_deleter to be protected where they could otherwise 339be private. 340 </para> 341 </listitem> 342</varlistentry> 343 344</variablelist> 345 346</section> 347 348</section> 349 350<section xml:id="shared_ptr.using"><info><title>Use</title></info> 351 352 353 <section><info><title>Examples</title></info> 354 355 <para> 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> 359 and 360 <filename class="directory">testsuite/20_util/weak_ptr</filename>. 361 </para> 362 </section> 363 364 <section><info><title>Unresolved Issues</title></info> 365 366 <para> 367 The <emphasis><classname>shared_ptr</classname> atomic access</emphasis> 368 clause in the C++11 standard is not implemented in GCC. 369 </para> 370 371 <para> 372 The <type>_S_single</type> policy uses atomics when used in MT 373 code, because it uses the same dispatcher functions that check 374 <function>__gthread_active_p()</function>. This could be 375 addressed by providing template specialisations for some members 376 of <classname>_Sp_counted_base<_S_single></classname>. 377 </para> 378 379 <para> 380 Unlike Boost, this implementation does not use separate classes 381 for the pointer+deleter and pointer+deleter+allocator cases in 382 C++11 mode, combining both into _Sp_counted_deleter and using 383 <classname>allocator</classname> when the user doesn't specify 384 an allocator. If it was found to be beneficial an additional 385 class could easily be added. With the current implementation, 386 the _Sp_counted_deleter and __shared_count constructors taking a 387 custom deleter but no allocator are technically redundant and 388 could be removed, changing callers to always specify an 389 allocator. If a separate pointer+deleter class was added the 390 __shared_count constructor would be needed, so it has been kept 391 for now. 392 </para> 393 394 <para> 395 The hack used to get the address of the managed object from 396 <function>_Sp_counted_ptr_inplace::_M_get_deleter()</function> 397 is accessible to users. This could be prevented if 398 <function>get_deleter<_Sp_make_shared_tag>()</function> 399 always returned NULL, since the hack only needs to work at a 400 lower level, not in the public API. This wouldn't be difficult, 401 but hasn't been done since there is no danger of accidental 402 misuse: users already know they are relying on unsupported 403 features if they refer to implementation details such as 404 _Sp_make_shared_tag. 405 </para> 406 407 <para> 408 tr1::_Sp_deleter could be a private member of tr1::__shared_count but it 409 would alter the ABI. 410 </para> 411 412 </section> 413 414</section> 415 416<section xml:id="shared_ptr.ack"><info><title>Acknowledgments</title></info> 417 418 419 <para> 420 The original authors of the Boost shared_ptr, which is really nice 421 code to work with, Peter Dimov in particular for his help and 422 invaluable advice on thread safety. Phillip Jordan and Paolo 423 Carlini for the lock policy implementation. 424 </para> 425 426</section> 427 428<bibliography xml:id="shared_ptr.biblio"><info><title>Bibliography</title></info> 429 430 431 <biblioentry> 432 <title> 433 <link xmlns:xlink="http://www.w3.org/1999/xlink" 434 xlink:href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm"> 435 Improving shared_ptr for C++0x, Revision 2 436 </link> 437 </title> 438 439 <subtitle> 440 N2351 441 </subtitle> 442 </biblioentry> 443 444 <biblioentry> 445 <title> 446 <link xmlns:xlink="http://www.w3.org/1999/xlink" 447 xlink:href="http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html"> 448 C++ Standard Library Active Issues List 449 </link> 450 </title> 451 452 <subtitle> 453 N2456 454 </subtitle> 455 </biblioentry> 456 457 <biblioentry> 458 <title> 459 <link xmlns:xlink="http://www.w3.org/1999/xlink" 460 xlink:href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf"> 461 Working Draft, Standard for Programming Language C++ 462 </link> 463 </title> 464 <subtitle> 465 N2461 466 </subtitle> 467 </biblioentry> 468 469 <biblioentry> 470 <title> 471 <link xmlns:xlink="http://www.w3.org/1999/xlink" 472 xlink:href="http://boost.org/libs/smart_ptr/shared_ptr.htm"> 473 Boost C++ Libraries documentation, shared_ptr 474 </link> 475 </title> 476 477 <subtitle> 478 N2461 479 </subtitle> 480 </biblioentry> 481 482</bibliography> 483 484</section> 485