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> 15 The shared_ptr class template stores a pointer, usually obtained via new, 16 and 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> 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 45 1.32 shared_ptr. 46 </para> 47 48 <para> 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 51 drops to zero. 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. 55 </para> 56 57 </section> 58 59 <section xml:id="shared_ptr.impl"><info><title>Implementation</title></info> 60 61 62 <section xml:id="shared_ptr.hier"><info><title>Class Hierarchy</title></info> 63 64 65 <para> 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 71 resource. 72 </para> 73 74 <variablelist> 75 76 <varlistentry> 77 <term><classname>_Sp_counted_base<Lp></classname></term> 78 <listitem> 79 <para> 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. 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> 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. 102 </para> 103 </listitem> 104 </varlistentry> 105 106 <varlistentry> 107 <term><classname>_Sp_counted_ptr<Ptr, Lp></classname></term> 108 <listitem> 109 <para> 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 113 allocator. 114 </para> 115 </listitem> 116 </varlistentry> 117 118 <varlistentry> 119 <term><classname>_Sp_counted_deleter<Ptr, Deleter, Alloc></classname></term> 120 <listitem> 121 <para> 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. 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> 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. 142 </para> 143 </listitem> 144 </varlistentry> 145 146 </variablelist> 147 148 <para> 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. 153 </para> 154 155 156 </section> 157 158 <section xml:id="shared_ptr.thread"><info><title>Thread Safety</title></info> 159 160 <para> 161 The 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. 167 </para> 168 169 <programlisting> 170 shared_ptr<A> a(new A); 171 shared_ptr<A> b(a); 172 173 // Thread 1 // Thread 2 174 a.reset(); b.reset(); 175 </programlisting> 176 177 <para> 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 185 job!) 186 On multi-processor systems memory synchronisation may be needed so that 187 reference-count updates and the destruction of the managed resource are 188 race-free. 189 </para> 190 191 <para> 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. 200 </para> 201 <para> 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. 212 </para> 213 214 </section> 215 216 <section xml:id="shared_ptr.policy"><info><title>Selecting Lock Policy</title></info> 217 218 219 <para> 220 </para> 221 222 <para> 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: 237 </para> 238 239 <orderedlist> 240 <listitem> 241 <para> 242 <constant>_S_atomic</constant> 243 </para> 244 <para> 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="http://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 249 synchronisation. 250 </para> 251 </listitem> 252 253 <listitem> 254 <para> 255 <constant>_S_mutex</constant> 256 </para> 257 <para> 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. 261 </para> 262 </listitem> 263 264 <listitem> 265 <para> 266 <constant>_S_single</constant> 267 </para> 268 <para> 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>. 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 xml:id="shared_ptr.rel"><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> 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. 300 </para> 301 </listitem> 302 </varlistentry> 303 304 <varlistentry> 305 <term><code>enable_shared_from_this</code></term> 306 <listitem> 307 <para> 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 312 policy. 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> 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 339 be 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 xml:id="shared_ptr.examples"><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 xml:id="shared_ptr.issues"><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 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 383 for now. 384 </para> 385 386 <para> 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 396 _Sp_make_shared_tag. 397 </para> 398 399 <para> 400 tr1::_Sp_deleter could be a private member of tr1::__shared_count but it 401 would alter the ABI. 402 </para> 403 404 </section> 405 406 </section> 407 408 <section xml:id="shared_ptr.ack"><info><title>Acknowledgments</title></info> 409 410 411 <para> 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. 416 </para> 417 418 </section> 419 420 <bibliography xml:id="shared_ptr.biblio"><info><title>Bibliography</title></info> 421 422 423 <biblioentry> 424 <title> 425 <link xmlns:xlink="http://www.w3.org/1999/xlink" 426 xlink:href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm"> 427 Improving shared_ptr for C++0x, Revision 2 428 </link> 429 </title> 430 431 <subtitle> 432 N2351 433 </subtitle> 434 </biblioentry> 435 436 <biblioentry> 437 <title> 438 <link xmlns:xlink="http://www.w3.org/1999/xlink" 439 xlink:href="http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2456.html"> 440 C++ Standard Library Active Issues List 441 </link> 442 </title> 443 444 <subtitle> 445 N2456 446 </subtitle> 447 </biblioentry> 448 449 <biblioentry> 450 <title> 451 <link xmlns:xlink="http://www.w3.org/1999/xlink" 452 xlink:href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf"> 453 Working Draft, Standard for Programming Language C++ 454 </link> 455 </title> 456 <subtitle> 457 N2461 458 </subtitle> 459 </biblioentry> 460 461 <biblioentry> 462 <title> 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 466 </link> 467 </title> 468 469 <subtitle> 470 N2461 471 </subtitle> 472 </biblioentry> 473 474 </bibliography> 475 476 </section> 477