1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <title>shared_ptr</title>
5 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
7 <body text="#000000" bgcolor="#ffffff" link="#0000ff" vlink="#0000ff">
8 <h1><img height="86" alt="boost.png (6897 bytes)" src="../../boost.png"
9 width="277" align="middle" border="0">shared_ptr class template</h1>
10 <p><a href="#Introduction">Introduction</a><br>
11 <a href="#BestPractices">Best Practices</a><br>
12 <a href="#Synopsis">Synopsis</a><br>
13 <a href="#Members">Members</a><br>
14 <a href="#functions">Free Functions</a><br>
15 <a href="#example">Example</a><br>
16 <a href="#HandleBody">Handle/Body Idiom</a><br>
17 <a href="#ThreadSafety">Thread Safety</a><br>
18 <a href="#FAQ">Frequently Asked Questions</a><br>
19 <a href="smarttests.htm">Smart Pointer Timings</a><br>
20 <a href="sp_techniques.html">Programming Techniques</a></p>
21 <h2 id="Introduction">Introduction</h2>
22 <p>The <code>shared_ptr</code> class template stores a pointer to a dynamically allocated
23 object, typically with a C++ <em>new-expression</em>. The object pointed to is
24 guaranteed to be deleted when the last <code>shared_ptr</code> pointing to it is
25 destroyed or reset.</p>
26 <blockquote><em>Example:</em><br><pre>shared_ptr<X> p1( new X );
27 shared_ptr<void> p2( new int(5) );
30 <p><code>shared_ptr</code> deletes the exact pointer that has been passed at construction time,
31 complete with its original type, regardless of the template parameter. In the second example above,
32 when <code>p2</code> is destroyed or reset, it will call <code>delete</code> on the original <code>int*</code>
33 that has been passed to the constructor, even though <code>p2</code> itself is of type
34 <code>shared_ptr<void></code> and stores a pointer of type <code>void*</code>.</p>
36 <p>Every <code>shared_ptr</code> meets the <code>CopyConstructible</code>, <code>MoveConstructible</code>,
37 <code>CopyAssignable</code> and <code>MoveAssignable</code>
38 requirements of the C++ Standard Library, and can be used in standard
39 library containers. Comparison operators are supplied so that <code>shared_ptr</code>
40 works with the standard library's associative containers.</p>
41 <p>Because the implementation uses reference counting, cycles of <code>shared_ptr</code> instances
42 will not be reclaimed. For example, if <code>main()</code> holds a <code>shared_ptr</code> to
43 <code>A</code>, which directly or indirectly holds a <code>shared_ptr</code> back to <code>A</code>,
44 <code>A</code>'s use count will be 2. Destruction of the original <code>shared_ptr</code> will
45 leave <code>A</code> dangling with a use count of 1. Use <a href="weak_ptr.htm">weak_ptr</a>
46 to "break cycles."</p>
47 <p>The class template is parameterized on <code>T</code>, the type of the object pointed
48 to. <code>shared_ptr</code> and most of its member functions place no
49 requirements on <code>T</code>; it is allowed to be an incomplete type, or
50 <code>void</code>. Member functions that do place additional requirements
51 (<a href="#pointer_constructor">constructors</a>, <a href="#reset">reset</a>) are explicitly
53 <p><code>shared_ptr<T></code> can be implicitly converted to <code>shared_ptr<U></code>
54 whenever <code>T*</code> can be implicitly converted to <code>U*</code>.
55 In particular, <code>shared_ptr<T></code> is implicitly convertible
56 to <code>shared_ptr<T const></code>, to <code>shared_ptr<U></code>
57 where <code>U</code> is an accessible base of <code>T</code>, and to <code>
58 shared_ptr<void></code>.</p>
59 <p><code>shared_ptr</code> is now part of the C++11 Standard, as <code>std::shared_ptr</code>.</p>
60 <p>Starting with Boost release 1.53, <code>shared_ptr</code> can be used to hold a pointer to a dynamically
61 allocated array. This is accomplished by using an array type (<code>T[]</code> or <code>T[N]</code>) as
62 the template parameter. There is almost no difference between using an unsized array, <code>T[]</code>,
63 and a sized array, <code>T[N]</code>; the latter just enables <code>operator[]</code> to perform a range check
65 <blockquote><em>Example:</em><br><pre>shared_ptr<double[1024]> p1( new double[1024] );
66 shared_ptr<double[]> p2( new double[n] );
69 <h2 id="BestPractices">Best Practices</h2>
70 <p>A simple guideline that nearly eliminates the possibility of memory leaks is:
71 always use a named smart pointer variable to hold the result of <code>new</code>.
72 Every occurence of the <code>new</code> keyword in the code should have the
74 <pre>shared_ptr<T> p(new Y);</pre>
75 <p>It is, of course, acceptable to use another smart pointer in place of <code>shared_ptr</code>
76 above; having <code>T</code> and <code>Y</code> be the same type, or
77 passing arguments to <code>Y</code>'s constructor is also OK.</p>
78 <p>If you observe this guideline, it naturally follows that you will have no
79 explicit <code>delete</code> statements; <code>try/catch</code> constructs will
81 <p>Avoid using unnamed <code>shared_ptr</code> temporaries to save typing; to
82 see why this is dangerous, consider this example:</p>
83 <pre>void f(shared_ptr<int>, int);
88 shared_ptr<int> p( new int(2) );
94 f( shared_ptr<int>( new int(2) ), g() );
97 <p>The function <code>ok</code> follows the guideline to the letter, whereas
98 <code>bad</code> constructs the temporary <code>shared_ptr</code> in place,
99 admitting the possibility of a memory leak. Since function arguments are
100 evaluated in unspecified order, it is possible for <code>new int(2)</code> to
101 be evaluated first, <code>g()</code> second, and we may never get to the
102 <code>shared_ptr</code>constructor if <code>g</code> throws an exception.
103 See <a href="http://www.gotw.ca/gotw/056.htm">Herb Sutter's treatment</a> (also <a href="http://www.cuj.com/reference/articles/2002/0212/0212_sutter.htm">
104 here</a>) of the issue for more information.</p>
105 <p>The exception safety problem described above may also be eliminated by using
106 the <a href="make_shared.html"><code>make_shared</code></a>
107 or <a href="make_shared.html"><code>allocate_shared</code></a>
108 factory functions defined in <code>boost/make_shared.hpp</code>.
109 These factory functions also provide an efficiency benefit by consolidating allocations.</p>
110 <h2 id="Synopsis">Synopsis</h2>
111 <pre>namespace boost {
113 class bad_weak_ptr: public std::exception;
115 template<class T> class <a href="weak_ptr.htm" >weak_ptr</a>;
117 template<class T> class shared_ptr {
121 typedef <em>see below</em> <a href="#element_type" >element_type</a>;
123 <a href="#default_constructor" >shared_ptr</a>(); // never throws
124 <a href="#default_constructor" >shared_ptr</a>(std::nullptr_t); // never throws
126 template<class Y> explicit <a href="#pointer_constructor" >shared_ptr</a>(Y * p);
127 template<class Y, class D> <a href="#deleter_constructor" >shared_ptr</a>(Y * p, D d);
128 template<class Y, class D, class A> <a href="#deleter_constructor" >shared_ptr</a>(Y * p, D d, A a);
129 template<class D> <a href="#deleter_constructor" >shared_ptr</a>(std::nullptr_t p, D d);
130 template<class D, class A> <a href="#deleter_constructor" >shared_ptr</a>(std::nullptr_t p, D d, A a);
132 <a href="#destructor" >~shared_ptr</a>(); // never throws
134 <a href="#copy_constructor" >shared_ptr</a>(shared_ptr const & r); // never throws
135 template<class Y> <a href="#copy_constructor" >shared_ptr</a>(shared_ptr<Y> const & r); // never throws
137 <a href="#move_constructor" >shared_ptr</a>(shared_ptr && r); // never throws
138 template<class Y> <a href="#move_constructor" >shared_ptr</a>(shared_ptr<Y> && r); // never throws
140 template<class Y> <a href="#aliasing_constructor" >shared_ptr</a>(shared_ptr<Y> const & r, element_type * p); // never throws
142 template<class Y> explicit <a href="#weak_ptr_constructor" >shared_ptr</a>(<a href="weak_ptr.htm" >weak_ptr</a><Y> const & r);
144 template<class Y> explicit <a href="#auto_ptr_constructor" >shared_ptr</a>(std::auto_ptr<Y> & r);
145 template<class Y> <a href="#auto_ptr_constructor" >shared_ptr</a>(std::auto_ptr<Y> && r);
147 template<class Y, class D> <a href="#unique_ptr_constructor" >shared_ptr</a>(std::unique_ptr<Y, D> && r);
149 shared_ptr & <a href="#assignment" >operator=</a>(shared_ptr const & r); // never throws
150 template<class Y> shared_ptr & <a href="#assignment" >operator=</a>(shared_ptr<Y> const & r); // never throws
152 shared_ptr & <a href="#assignment" >operator=</a>(shared_ptr const && r); // never throws
153 template<class Y> shared_ptr & <a href="#assignment" >operator=</a>(shared_ptr<Y> const && r); // never throws
155 template<class Y> shared_ptr & <a href="#assignment" >operator=</a>(std::auto_ptr<Y> & r);
156 template<class Y> shared_ptr & <a href="#assignment" >operator=</a>(std::auto_ptr<Y> && r);
158 template<class Y, class D> shared_ptr & <a href="#assignment" >operator=</a>(std::unique_ptr<Y, D> && r);
160 shared_ptr & <a href="#assignment" >operator=</a>(std::nullptr_t); // never throws
162 void <a href="#reset" >reset</a>(); // never throws
164 template<class Y> void <a href="#reset" >reset</a>(Y * p);
165 template<class Y, class D> void <a href="#reset" >reset</a>(Y * p, D d);
166 template<class Y, class D, class A> void <a href="#reset" >reset</a>(Y * p, D d, A a);
168 template<class Y> void <a href="#reset" >reset</a>(shared_ptr<Y> const & r, element_type * p); // never throws
170 T & <a href="#indirection" >operator*</a>() const; // never throws; only valid when T is not an array type
171 T * <a href="#indirection" >operator-></a>() const; // never throws; only valid when T is not an array type
173 element_type & <a href="#indirection" >operator[]</a>(std::ptrdiff_t i) const; // never throws; only valid when T is an array type
175 element_type * <a href="#get" >get</a>() const; // never throws
177 bool <a href="#unique" >unique</a>() const; // never throws
178 long <a href="#use_count" >use_count</a>() const; // never throws
180 explicit <a href="#conversions" >operator bool</a>() const; // never throws
182 void <a href="#swap" >swap</a>(shared_ptr & b); // never throws
184 template<class Y> bool <a href="#owner_before" >owner_before</a>(shared_ptr<Y> const & rhs) const; // never throws
185 template<class Y> bool <a href="#owner_before" >owner_before</a>(weak_ptr<Y> const & rhs) const; // never throws
188 template<class T, class U>
189 bool <a href="#comparison" >operator==</a>(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws
191 template<class T, class U>
192 bool <a href="#comparison" >operator!=</a>(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws
194 template<class T, class U>
195 bool <a href="#comparison" >operator<</a>(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws
197 template<class T>
198 bool <a href="#comparison" >operator==</a>(shared_ptr<T> const & p, std::nullptr_t); // never throws
200 template<class T>
201 bool <a href="#comparison" >operator==</a>(std::nullptr_t, shared_ptr<T> const & p); // never throws
203 template<class T>
204 bool <a href="#comparison" >operator!=</a>(shared_ptr<T> const & p, std::nullptr_t); // never throws
206 template<class T>
207 bool <a href="#comparison" >operator!=</a>(std::nullptr_t, shared_ptr<T> const & p); // never throws
209 template<class T> void <a href="#free-swap" >swap</a>(shared_ptr<T> & a, shared_ptr<T> & b); // never throws
211 template<class T> typename shared_ptr<T>::element_type * <a href="#get_pointer" >get_pointer</a>(shared_ptr<T> const & p); // never throws
213 template<class T, class U>
214 shared_ptr<T> <a href="#static_pointer_cast" >static_pointer_cast</a>(shared_ptr<U> const & r); // never throws
216 template<class T, class U>
217 shared_ptr<T> <a href="#const_pointer_cast" >const_pointer_cast</a>(shared_ptr<U> const & r); // never throws
219 template<class T, class U>
220 shared_ptr<T> <a href="#dynamic_pointer_cast" >dynamic_pointer_cast</a>(shared_ptr<U> const & r); // never throws
222 template<class T, class U>
223 shared_ptr<T> <a href="#reinterpret_pointer_cast" >reinterpet_pointer_cast</a>(shared_ptr<U> const & r); // never throws
225 template<class E, class T, class Y>
226 std::basic_ostream<E, T> & <a href="#insertion-operator" >operator<<</a> (std::basic_ostream<E, T> & os, shared_ptr<Y> const & p);
228 template<class D, class T>
229 D * <a href="#get_deleter">get_deleter</a>(shared_ptr<T> const & p);
231 <h2 id="Members">Members</h2>
232 <h3 id="element_type">element_type</h3>
233 <pre>typedef <em>...</em> element_type;</pre>
235 <p><code>element_type</code> is <code>T</code> when <code>T</code> is not an array type,
236 and <code>U</code> when <code>T</code> is <code>U[]</code> or <code>U[N]</code>.</p>
238 <h3 id="default_constructor">default constructor</h3>
239 <pre>shared_ptr(); // never throws
240 shared_ptr(std::nullptr_t); // never throws</pre>
242 <p><b>Effects:</b> Constructs an <em>empty</em> <code>shared_ptr</code>.</p>
243 <p><b>Postconditions:</b> <code>use_count() == 0 && get() == 0</code>.</p>
244 <p><b>Throws:</b> nothing.</p>
246 <p><em>[The nothrow guarantee is important, since <code>reset()</code> is specified
247 in terms of the default constructor; this implies that the constructor must not
248 allocate memory.]</em></p>
249 <h3 id="pointer_constructor">pointer constructor</h3>
250 <pre>template<class Y> explicit shared_ptr(Y * p);</pre>
252 <p><b>Requirements:</b>
253 <code>Y</code> must be a complete type.
254 The expression <code>delete[] p</code>, when <code>T</code> is an array type, or <code>delete p</code>,
255 when <code>T</code> is not an array type,
256 must be well-formed, must not invoke undefined behavior, and must not throw exceptions.
257 When <code>T</code> is <code>U[N]</code>, <code>Y (*) [N]</code> must be convertible to <code>T*</code>;
258 when <code>T</code> is <code>U[]</code>, <code>Y (*) []</code> must be convertible to <code>T*</code>;
259 otherwise, <code>Y*</code> must be convertible to <code>T*</code>.
262 When <code>T</code> is not an array type, constructs a <code>shared_ptr</code> that <em>owns</em>
263 the pointer <code>p</code>.
264 Otherwise, constructs a <code>shared_ptr</code> that <em>owns</em>
265 <code>p</code> and a deleter of an unspecified type that calls <code>delete[] p</code>.</p>
266 <p><b>Postconditions:</b> <code>use_count() == 1 && get() == p</code>.
267 If <code>T</code> is not an array type and <code>p</code> is unambiguously convertible to <code>
268 <a href="enable_shared_from_this.html">enable_shared_from_this</a><V>*</code>
269 for some <code>V</code>, <code>p->shared_from_this()</code> returns a copy of
270 <code>*this</code>.</p>
271 <p><b>Throws:</b> <code>std::bad_alloc</code>, or an implementation-defined
272 exception when a resource other than memory could not be obtained.</p>
273 <p><b>Exception safety:</b> If an exception is thrown, the constructor calls
274 <code>delete[] p</code>, when <code>T</code> is an array type,
275 or <code>delete p</code>, when <code>T</code> is not an array type.</p>
276 <p><b>Notes:</b> <code>p</code> must be a pointer to an object that was
277 allocated via a C++ <code>new</code> expression or be 0. The postcondition that <a href="#use_count">
278 use count</a> is 1 holds even if <code>p</code> is 0; invoking <code>delete</code>
279 on a pointer that has a value of 0 is harmless.</p>
281 <p><em>[This constructor is a template in order to remember the actual
282 pointer type passed. The destructor will call <code>delete</code> with the
283 same pointer, complete with its original type, even when <code>T</code> does
284 not have a virtual destructor, or is <code>void</code>.]</em></p>
285 <h3 id="deleter_constructor">constructors taking a deleter</h3>
286 <pre>template<class Y, class D> shared_ptr(Y * p, D d);
287 template<class Y, class D, class A> shared_ptr(Y * p, D d, A a);
288 template<class D> shared_ptr(std::nullptr_t p, D d);
289 template<class D, class A> shared_ptr(std::nullptr_t p, D d, A a);</pre>
291 <p><b>Requirements:</b>
292 <code>D</code> must be <code>CopyConstructible</code>. The copy constructor and destructor
293 of <code>D</code> must not throw. The expression <code>d(p)</code> must be
294 well-formed, must not invoke undefined behavior, and must not throw exceptions.
295 <code>A</code> must be an <em>Allocator</em>, as described in section 20.1.5
296 (<code>Allocator requirements</code>) of the C++ Standard.
297 When <code>T</code> is <code>U[N]</code>, <code>Y (*) [N]</code> must be convertible to <code>T*</code>;
298 when <code>T</code> is <code>U[]</code>, <code>Y (*) []</code> must be convertible to <code>T*</code>;
299 otherwise, <code>Y*</code> must be convertible to <code>T*</code>.
301 <p><b>Effects:</b> Constructs a <code>shared_ptr</code> that <em>owns</em> the pointer <code>
302 p</code> and the deleter <code>d</code>. The constructors taking an allocator <code>a</code>
303 allocate memory using a copy of <code>a</code>.</p>
304 <p><b>Postconditions:</b> <code>use_count() == 1 && get() == p</code>.
305 If <code>T</code> is not an array type and <code>p</code> is unambiguously convertible to <code>
306 <a href="enable_shared_from_this.html">enable_shared_from_this</a><V>*</code>
307 for some <code>V</code>, <code>p->shared_from_this()</code> returns a copy of
308 <code>*this</code>.</p>
309 <p><b>Throws:</b> <code>std::bad_alloc</code>, or an implementation-defined
310 exception when a resource other than memory could not be obtained.</p>
311 <p><b>Exception safety:</b> If an exception is thrown, <code>d(p)</code> is called.</p>
312 <p><b>Notes:</b> When the the time comes to delete the object pointed to by <code>p</code>,
313 the stored copy of <code>d</code> is invoked with the stored copy of <code>p</code>
316 <p><em>[Custom deallocators allow a factory function returning a <code>shared_ptr</code>
317 to insulate the user from its memory allocation strategy. Since the deallocator
318 is not part of the type, changing the allocation strategy does not break source
319 or binary compatibility, and does not require a client recompilation. For
320 example, a "no-op" deallocator is useful when returning a <code>shared_ptr</code>
321 to a statically allocated object, and other variations allow a <code>shared_ptr</code>
322 to be used as a wrapper for another smart pointer, easing interoperability.</em></p>
323 <p><em>The support for custom deallocators does not impose significant overhead. Other <code>
324 shared_ptr</code> features still require a deallocator to be kept.</em></p>
325 <p><em>The requirement that the copy constructor of <code>D</code> does not throw comes from
326 the pass by value. If the copy constructor throws, the pointer would leak.]</em></p>
327 <h3 id="copy_constructor">copy and converting constructors</h3>
328 <pre>shared_ptr(shared_ptr const & r); // never throws
329 template<class Y> shared_ptr(shared_ptr<Y> const & r); // never throws</pre>
331 <p><b>Requires:</b> <code>Y*</code> should be convertible to <code>T*</code>.</p>
332 <p><b>Effects:</b> If <code>r</code> is <em>empty</em>, constructs an <em>empty</em> <code>shared_ptr</code>;
333 otherwise, constructs a <code>shared_ptr</code> that <em>shares ownership</em> with <code>r</code>.</p>
334 <p><b>Postconditions:</b> <code>get() == r.get() && use_count() ==
335 r.use_count()</code>.</p>
336 <p><b>Throws:</b> nothing.</p>
338 <h3 id="move_constructor">move constructors</h3>
339 <pre>shared_ptr(shared_ptr && r); // never throws
340 template<class Y> shared_ptr(shared_ptr<Y> && r); // never throws</pre>
342 <p><b>Requires:</b> <code>Y*</code> should be convertible to <code>T*</code>.</p>
343 <p><b>Effects:</b> Move-constructs a <code>shared_ptr</code> from <code>r</code>.</p>
344 <p><b>Postconditions:</b> <code>*this</code> contains the old value of <code>r</code>. <code>r</code> is <em>empty</em> and <code>r.get() == 0</code>.</p>
345 <p><b>Throws:</b> nothing.</p>
347 <h3 id="aliasing_constructor">aliasing constructor</h3>
348 <pre>template<class Y> shared_ptr(shared_ptr<Y> const & r, element_type * p); // never throws</pre>
350 <p><b>Effects:</b> constructs a <code>shared_ptr</code> that <em>shares ownership</em> with
351 <code>r</code> and stores <code>p</code>.</p>
352 <p><b>Postconditions:</b> <code>get() == p && use_count() == r.use_count()</code>.</p>
353 <p><b>Throws:</b> nothing.</p>
355 <h3 id="weak_ptr_constructor">weak_ptr constructor</h3>
356 <pre>template<class Y> explicit shared_ptr(<a href="weak_ptr.htm" >weak_ptr</a><Y> const & r);</pre>
358 <p><b>Requires:</b> <code>Y*</code> should be convertible to <code>T*</code>.</p>
359 <p><b>Effects:</b> Constructs a <code>shared_ptr</code> that <em>shares ownership</em> with
360 <code>r</code> and stores a copy of the pointer stored in <code>r</code>.</p>
361 <p><b>Postconditions:</b> <code>use_count() == r.use_count()</code>.</p>
362 <p><b>Throws:</b> <code>bad_weak_ptr</code> when <code>r.use_count() == 0</code>.</p>
363 <p><b>Exception safety:</b> If an exception is thrown, the constructor has no
366 <h3 id="auto_ptr_constructor">auto_ptr constructors</h3>
367 <pre>template<class Y> shared_ptr(std::auto_ptr<Y> & r);
368 template<class Y> shared_ptr(std::auto_ptr<Y> && r);</pre>
370 <p><b>Requires:</b> <code>Y*</code> should be convertible to <code>T*</code>.</p>
371 <p><b>Effects:</b> Constructs a <code>shared_ptr</code>, as if by storing a copy of <code>r.release()</code>.</p>
372 <p><b>Postconditions:</b> <code>use_count() == 1</code>.</p>
373 <p><b>Throws:</b> <code>std::bad_alloc</code>, or an implementation-defined
374 exception when a resource other than memory could not be obtained.</p>
375 <p><b>Exception safety:</b> If an exception is thrown, the constructor has no
378 <h3 id="unique_ptr_constructor">unique_ptr constructor</h3>
379 <pre>template<class Y, class D> shared_ptr(std::unique_ptr<Y, D> && r);</pre>
381 <p><b>Requires:</b> <code>Y*</code> should be convertible to <code>T*</code>.</p>
383 Equivalent to <code>shared_ptr(r.release(), r.get_deleter())</code> when <code>D</code> is not a reference type.
384 Otherwise, equivalent to <code>shared_ptr(r.release(), <em>del</em>)</code>, where <em>del</em> is a deleter
385 that stores the reference <code>rd</code> returned from <code>r.get_deleter()</code> and <code>del(p)</code> calls <code>rd(p)</code>.</p>
386 <p><b>Postconditions:</b> <code>use_count() == 1</code>.</p>
387 <p><b>Throws:</b> <code>std::bad_alloc</code>, or an implementation-defined
388 exception when a resource other than memory could not be obtained.</p>
389 <p><b>Exception safety:</b> If an exception is thrown, the constructor has no
392 <h3 id="destructor">destructor</h3>
393 <pre>~shared_ptr(); // never throws</pre>
395 <p><b>Effects:</b></p>
398 If <code>*this</code> is <em>empty</em>, or <em>shares ownership</em> with
399 another <code>shared_ptr</code> instance (<code>use_count() > 1</code>),
400 there are no side effects.</li>
402 Otherwise, if <code>*this</code> <em>owns</em> a pointer <code>p</code>
403 and a deleter <code>d</code>, <code>d(p)</code>
406 Otherwise, <code>*this</code> <em>owns</em> a pointer <code>p</code>,
407 and <code>delete p</code> is called.</li>
409 <p><b>Throws:</b> nothing.</p>
411 <h3 id="assignment">assignment</h3>
412 <pre>shared_ptr & operator=(shared_ptr const & r); // never throws
413 template<class Y> shared_ptr & operator=(shared_ptr<Y> const & r); // never throws
414 template<class Y> shared_ptr & operator=(std::auto_ptr<Y> & r);</pre>
416 <p><b>Effects:</b> Equivalent to <code>shared_ptr(r).swap(*this)</code>.</p>
417 <p><b>Returns:</b> <code>*this</code>.</p>
418 <p><b>Notes:</b> The use count updates caused by the temporary object construction
419 and destruction are not considered observable side effects, and the
420 implementation is free to meet the effects (and the implied guarantees) via
421 different means, without creating a temporary. In particular, in the example:</p>
422 <pre>shared_ptr<int> p(new int);
423 shared_ptr<void> q(p);
427 <p>both assignments may be no-ops.</p>
429 <pre>shared_ptr & operator=(shared_ptr && r); // never throws
430 template<class Y> shared_ptr & operator=(shared_ptr<Y> && r); // never throws
431 template<class Y> shared_ptr & operator=(std::auto_ptr<Y> && r);
432 template<class Y, class D> shared_ptr & operator=(std::unique_ptr<Y, D> && r);</pre>
434 <p><b>Effects:</b> Equivalent to <code>shared_ptr(std::move(r)).swap(*this)</code>.</p>
435 <p><b>Returns:</b> <code>*this</code>.</p>
437 <pre>shared_ptr & operator=(std::nullptr_t); // never throws</pre>
439 <p><b>Effects:</b> Equivalent to <code>shared_ptr().swap(*this)</code>.</p>
440 <p><b>Returns:</b> <code>*this</code>.</p>
442 <h3 id="reset">reset</h3>
443 <pre>void reset(); // never throws</pre>
445 <p><b>Effects:</b> Equivalent to <code>shared_ptr().swap(*this)</code>.</p>
447 <pre>template<class Y> void reset(Y * p);</pre>
449 <p><b>Effects:</b> Equivalent to <code>shared_ptr(p).swap(*this)</code>.</p>
451 <pre>template<class Y, class D> void reset(Y * p, D d);</pre>
453 <p><b>Effects:</b> Equivalent to <code>shared_ptr(p, d).swap(*this)</code>.</p>
455 <pre>template<class Y, class D, class A> void reset(Y * p, D d, A a);</pre>
457 <p><b>Effects:</b> Equivalent to <code>shared_ptr(p, d, a).swap(*this)</code>.</p>
459 <pre>template<class Y> void reset(shared_ptr<Y> const & r, element_type * p); // never throws</pre>
461 <p><b>Effects:</b> Equivalent to <code>shared_ptr(r, p).swap(*this)</code>.</p>
463 <h3 id="indirection">indirection</h3>
464 <pre>T & operator*() const; // never throws</pre>
466 <p><b>Requirements:</b> <code>T</code> should not be an array type. The stored pointer must not be 0.</p>
467 <p><b>Returns:</b> a reference to the object pointed to by the stored pointer.</p>
468 <p><b>Throws:</b> nothing.</p>
470 <pre>T * operator->() const; // never throws</pre>
472 <p><b>Requirements:</b> <code>T</code> should not be an array type. The stored pointer must not be 0.</p>
473 <p><b>Returns:</b> the stored pointer.</p>
474 <p><b>Throws:</b> nothing.</p>
476 <pre>element_type & operator[](std::ptrdiff_t i) const; // never throws</pre>
478 <p><b>Requirements:</b> <code>T</code> should be an array type. The stored pointer must not be 0.
479 <code>i >= 0</code>. If <code>T</code> is <code>U[N]</code>, <code>i < N</code>.</p>
480 <p><b>Returns:</b> <code>get()[i]</code>.</p>
481 <p><b>Throws:</b> nothing.</p>
483 <h3 id="get">get</h3>
484 <pre>element_type * get() const; // never throws</pre>
486 <p><b>Returns:</b> the stored pointer.</p>
487 <p><b>Throws:</b> nothing.</p>
489 <h3 id="unique">unique</h3>
490 <pre>bool unique() const; // never throws</pre>
492 <p><b>Returns:</b> <code>use_count() == 1</code>.</p>
493 <p><b>Throws:</b> nothing.</p>
494 <p><b>Notes:</b> <code>unique()</code> may be faster than <code>use_count()</code>.
495 If you are using <code>unique()</code> to implement copy on write, do not rely
496 on a specific value when the stored pointer is zero.</p>
498 <h3 id="use_count">use_count</h3>
499 <pre>long use_count() const; // never throws</pre>
501 <p><b>Returns:</b> the number of <code>shared_ptr</code> objects, <code>*this</code> included,
502 that <i>share ownership</i> with <code>*this</code>, or 0 when <code>*this</code>
503 is <em>empty</em>.</p>
504 <p><b>Throws:</b> nothing.</p>
505 <p><b>Notes:</b> <code>use_count()</code> is not necessarily efficient. Use only
506 for debugging and testing purposes, not for production code.</p>
508 <h3 id="conversions">conversions</h3>
509 <pre>explicit operator bool() const; // never throws</pre>
511 <p><b>Returns:</b> <code>get() != 0</code>.</p>
512 <p><b>Throws:</b> nothing.</p>
513 <p><b>Notes:</b> This conversion operator allows <code>shared_ptr</code> objects to be
514 used in boolean contexts, like <code>if(p && p->valid()) {}</code>.</p>
516 <p><em>[The conversion to bool is not merely syntactic sugar. It allows <code>shared_ptr</code>s
517 to be declared in conditions when using <a href="#dynamic_pointer_cast">dynamic_pointer_cast</a>
518 or <a href="weak_ptr.htm#lock">weak_ptr::lock</a>.]</em></p>
519 <h3 id="swap">swap</h3>
520 <pre>void swap(shared_ptr & b); // never throws</pre>
522 <p><b>Effects:</b> Exchanges the contents of the two smart pointers.</p>
523 <p><b>Throws:</b> nothing.</p>
525 <h3 id="owner_before">swap</h3>
526 <pre>template<class Y> bool owner_before(shared_ptr<Y> const & rhs) const; // never throws
527 template<class Y> bool owner_before(weak_ptr<Y> const & rhs) const; // never throws</pre>
529 <p><b>Effects:</b> See the description of <a href="#comparison"><code>operator<</code></a>.</p>
530 <p><b>Throws:</b> nothing.</p>
532 <h2 id="functions">Free Functions</h2>
533 <h3 id="comparison">comparison</h3>
534 <pre>template<class T, class U>
535 bool operator==(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws</pre>
537 <p><b>Returns:</b> <code>a.get() == b.get()</code>.</p>
538 <p><b>Throws:</b> nothing.</p>
540 <pre>template<class T, class U>
541 bool operator!=(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws</pre>
543 <p><b>Returns:</b> <code>a.get() != b.get()</code>.</p>
544 <p><b>Throws:</b> nothing.</p>
546 <pre>template<class T>
547 bool operator==(shared_ptr<T> const & p, std::nullptr_t); // never throws
548 template<class T>
549 bool operator==(std::nullptr_t, shared_ptr<T> const & p); // never throws</pre>
551 <p><b>Returns:</b> <code>p.get() == 0</code>.</p>
552 <p><b>Throws:</b> nothing.</p>
554 <pre>template<class T>
555 bool operator!=(shared_ptr<T> const & p, std::nullptr_t); // never throws
556 template<class T>
557 bool operator!=(std::nullptr_t, shared_ptr<T> const & p); // never throws</pre>
559 <p><b>Returns:</b> <code>p.get() != 0</code>.</p>
560 <p><b>Throws:</b> nothing.</p>
562 <pre>template<class T, class U>
563 bool operator<(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws</pre>
565 <p><b>Returns:</b> an unspecified value such that</p>
568 <code>operator<</code> is a strict weak ordering as described in section 25.3 <code>[lib.alg.sorting]</code>
569 of the C++ standard;</li>
571 under the equivalence relation defined by <code>operator<</code>, <code>!(a
572 < b) && !(b < a)</code>, two <code>shared_ptr</code> instances
573 are equivalent if and only if they <em>share ownership</em> or are both <em>empty</em>.</li></ul>
574 <p><b>Throws:</b> nothing.</p>
575 <p><b>Notes:</b> Allows <code>shared_ptr</code> objects to be used as keys in
576 associative containers.</p>
578 <p><em>[<code>Operator<</code> has been preferred over a <code>std::less</code>
579 specialization for consistency and legality reasons, as <code>std::less</code>
580 is required to return the results of <code>operator<</code>, and many
581 standard algorithms use <code>operator<</code> instead of <code>std::less</code>
582 for comparisons when a predicate is not supplied. Composite objects, like <code>std::pair</code>,
583 also implement their <code>operator<</code> in terms of their contained
584 subobjects' <code>operator<</code>.</em></p>
585 <p><em>The rest of the comparison operators are omitted by design.]</em></p>
586 <h3 id="free-swap">swap</h3>
587 <pre>template<class T>
588 void swap(shared_ptr<T> & a, shared_ptr<T> & b); // never throws</pre>
590 <p><b>Effects:</b> Equivalent to <code>a.swap(b)</code>.</p>
591 <p><b>Throws:</b> nothing.</p>
592 <p><b>Notes:</b> Matches the interface of <code>std::swap</code>. Provided as an aid to
593 generic programming.</p>
595 <p><em>[<code>swap</code> is defined in the same namespace as <code>shared_ptr</code>
596 as this is currently the only legal way to supply a <code>swap</code> function
597 that has a chance to be used by the standard library.]</em></p>
598 <h3 id="get_pointer">get_pointer</h3>
599 <pre>template<class T>
600 typename shared_ptr<T>::element_type * get_pointer(shared_ptr<T> const & p); // never throws</pre>
602 <p><b>Returns:</b> <code>p.get()</code>.</p>
603 <p><b>Throws:</b> nothing.</p>
604 <p><b>Notes:</b> Provided as an aid to generic programming. Used by <a href="../bind/mem_fn.html">
607 <h3 id="static_pointer_cast">static_pointer_cast</h3>
608 <pre>template<class T, class U>
609 shared_ptr<T> static_pointer_cast(shared_ptr<U> const & r); // never throws</pre>
611 <p><b>Requires:</b> The expression <code>static_cast<T*>( (U*)0 )</code>
612 must be well-formed.</p>
613 <p><b>Returns:</b> <code>shared_ptr<T>( r, static_cast<typename shared_ptr<T>::element_type*>(r.get()) )</code>.</p>
614 <p><b>Throws:</b> nothing.</p>
615 <p><b>Notes:</b> the seemingly equivalent expression
616 <code>shared_ptr<T>(static_cast<T*>(r.get()))</code>
617 will eventually result in undefined behavior, attempting to delete the same
620 <h3 id="const_pointer_cast">const_pointer_cast</h3>
621 <pre>template<class T, class U>
622 shared_ptr<T> const_pointer_cast(shared_ptr<U> const & r); // never throws</pre>
624 <p><b>Requires:</b> The expression <code>const_cast<T*>( (U*)0 )</code>
625 must be well-formed.</p>
626 <p><b>Returns:</b> <code>shared_ptr<T>( r, const_cast<typename shared_ptr<T>::element_type*>(r.get()) )</code>.</p>
627 <p><b>Throws:</b> nothing.</p>
629 <h3 id="dynamic_pointer_cast">dynamic_pointer_cast</h3>
630 <pre>template<class T, class U>
631 shared_ptr<T> dynamic_pointer_cast(shared_ptr<U> const & r);</pre>
633 <p><b>Requires:</b> The expression <code>dynamic_cast<T*>( (U*)0 )</code>
634 must be well-formed.</p>
635 <p><b>Returns:</b></p>
638 When <code>dynamic_cast<typename shared_ptr<T>::element_type*>(r.get())</code> returns a nonzero value <code>p</code>,
639 <code>shared_ptr<T>(r, p)</code>;</li>
641 Otherwise, <code>shared_ptr<T>()</code>.</li></ul>
642 <p><b>Throws:</b> nothing.</p>
644 <h3 id="reinterpret_pointer_cast">reinterpret_pointer_cast</h3>
645 <pre>template<class T, class U>
646 shared_ptr<T> reinterpret_pointer_cast(shared_ptr<U> const & r); // never throws</pre>
648 <p><b>Requires:</b> The expression <code>reinterpret_cast<T*>( (U*)0 )</code>
649 must be well-formed.</p>
650 <p><b>Returns:</b> <code>shared_ptr<T>( r, reinterpret_cast<typename shared_ptr<T>::element_type*>(r.get()) )</code>.</p>
651 <p><b>Throws:</b> nothing.</p>
653 <h3 id="insertion-operator">operator<<</h3>
654 <pre>template<class E, class T, class Y>
655 std::basic_ostream<E, T> & operator<< (std::basic_ostream<E, T> & os, shared_ptr<Y> const & p);</pre>
657 <p><b>Effects:</b> <code>os << p.get();</code>.</p>
658 <p><b>Returns:</b> <code>os</code>.</p>
660 <h3 id="get_deleter">get_deleter</h3>
661 <pre>template<class D, class T>
662 D * get_deleter(shared_ptr<T> const & p);</pre>
664 <p><b>Returns:</b> If <code>*this</code> <em>owns</em> a deleter <code>d</code>
665 of type (cv-unqualified) <code>D</code>, returns <code>&d</code>;
666 otherwise returns 0.</p>
667 <p><b>Throws:</b> nothing.</p>
669 <h2 id="example">Example</h2>
670 <p>See <a href="example/shared_ptr_example.cpp">shared_ptr_example.cpp</a> for a
671 complete example program. The program builds a <code>std::vector</code> and <code>std::set</code>
672 of <code>shared_ptr</code> objects.</p>
673 <p>Note that after the containers have been populated, some of the <code>shared_ptr</code>
674 objects will have a use count of 1 rather than a use count of 2, since the set
675 is a <code>std::set</code> rather than a <code>std::multiset</code>, and thus does not
676 contain duplicate entries. Furthermore, the use count may be even higher at
677 various times while <code>push_back</code> and <code>insert</code> container operations are
678 performed. More complicated yet, the container operations may throw exceptions
679 under a variety of circumstances. Getting the memory management and exception
680 handling in this example right without a smart pointer would be a nightmare.</p>
681 <h2 id="HandleBody">Handle/Body Idiom</h2>
682 <p>One common usage of <code>shared_ptr</code> is to implement a handle/body (also called
683 pimpl) idiom which avoids exposing the body (implementation) in the header
685 <p>The <a href="example/shared_ptr_example2_test.cpp">shared_ptr_example2_test.cpp</a>
686 sample program includes a header file, <a href="example/shared_ptr_example2.hpp">shared_ptr_example2.hpp</a>,
687 which uses a <code>shared_ptr</code> to an incomplete type to hide the
688 implementation. The instantiation of member functions which require a complete
689 type occurs in the <a href="example/shared_ptr_example2.cpp">shared_ptr_example2.cpp</a>
690 implementation file. Note that there is no need for an explicit destructor.
691 Unlike <code>~scoped_ptr</code>, <code>~shared_ptr</code> does not require that <code>T</code> be a complete
693 <h2 id="ThreadSafety">Thread Safety</h2>
694 <p><code>shared_ptr</code> objects offer the same level of thread safety as
695 built-in types. A <code>shared_ptr</code> instance can be "read" (accessed
696 using only const operations) simultaneously by multiple threads. Different <code>shared_ptr</code>
697 instances can be "written to" (accessed using mutable operations such as <code>operator=
698 </code>or <code>reset</code>) simultaneously by multiple threads (even
699 when these instances are copies, and share the same reference count
701 <p>Any other simultaneous accesses result in undefined behavior.</p>
703 <pre>shared_ptr<int> p(new int(42));
708 shared_ptr<int> p2(p); // reads p
711 shared_ptr<int> p3(p); // OK, multiple reads are safe
716 p.reset(new int(1912)); // writes p
719 p2.reset(); // OK, writes p2
724 p = p3; // reads p3, writes p
727 p3.reset(); // writes p3; undefined, simultaneous read/write
732 p3 = p2; // reads p2, writes p3
735 // p2 goes out of scope: undefined, the destructor is considered a "write access"
740 p3.reset(new int(1));
743 p3.reset(new int(2)); // undefined, multiple writes
746 <p>Starting with Boost release 1.33.0, <code>shared_ptr</code> uses a lock-free
747 implementation on most common platforms.</p>
748 <p>If your program is single-threaded and does not link to any libraries that might
749 have used <code>shared_ptr</code> in its default configuration, you can <code>
750 #define</code> the macro <code>BOOST_SP_DISABLE_THREADS</code> on a
751 project-wide basis to switch to ordinary non-atomic reference count updates.</p>
752 <p>(Defining <code>BOOST_SP_DISABLE_THREADS</code> in some, but not all,
753 translation units is technically a violation of the One Definition Rule and
754 undefined behavior. Nevertheless, the implementation attempts to do its best to
755 accommodate the request to use non-atomic updates in those translation units.
756 No guarantees, though.)</p>
757 <p>You can define the macro <code>BOOST_SP_USE_PTHREADS</code> to turn off the
758 lock-free platform-specific implementation and fall back to the generic
759 <code>pthread_mutex_t</code>-based code.</p>
760 <h2 id="FAQ">Frequently Asked Questions</h2>
761 <p><b>Q.</b> There are several variations of shared pointers, with different
762 tradeoffs; why does the smart pointer library supply only a single
763 implementation? It would be useful to be able to experiment with each type so
764 as to find the most suitable for the job at hand?</p>
766 <b>A.</b> An important goal of <code>shared_ptr</code> is to provide a
767 standard shared-ownership pointer. Having a single pointer type is important
768 for stable library interfaces, since different shared pointers typically cannot
769 interoperate, i.e. a reference counted pointer (used by library A) cannot share
770 ownership with a linked pointer (used by library B.)
772 <p><b>Q.</b> Why doesn't <code>shared_ptr</code> have template parameters supplying
773 traits or policies to allow extensive user customization?</p>
775 <b>A.</b> Parameterization discourages users. The <code>shared_ptr</code> template is
776 carefully crafted to meet common needs without extensive parameterization. Some
777 day a highly configurable smart pointer may be invented that is also very easy
778 to use and very hard to misuse. Until then, <code>shared_ptr</code> is the smart
779 pointer of choice for a wide range of applications. (Those interested in policy
780 based smart pointers should read <a href="http://www.awprofessional.com/bookstore/product.asp?isbn=0201704315&rl=1">
781 Modern C++ Design</a> by Andrei Alexandrescu.)
783 <p><b>Q.</b> I am not convinced. Default parameters can be used where appropriate
784 to hide the complexity. Again, why not policies?</p>
786 <b>A.</b> Template parameters affect the type. See the answer to the first
789 <p><b>Q.</b> Why doesn't <code>shared_ptr</code> use a linked list implementation?</p>
791 <b>A.</b> A linked list implementation does not offer enough advantages to
792 offset the added cost of an extra pointer. See <a href="smarttests.htm">timings</a>
793 page. In addition, it is expensive to make a linked list implementation thread
796 <p><b>Q.</b> Why doesn't <code>shared_ptr</code> (or any of the other Boost smart
797 pointers) supply an automatic conversion to <code>T*</code>?</p>
799 <b>A.</b> Automatic conversion is believed to be too error prone.
801 <p><b>Q.</b> Why does <code>shared_ptr</code> supply <code>use_count()</code>?</p>
803 <b>A.</b> As an aid to writing test cases and debugging displays. One of the
804 progenitors had <code>use_count()</code>, and it was useful in tracking down bugs in a
805 complex project that turned out to have cyclic-dependencies.
807 <p><b>Q.</b> Why doesn't <code>shared_ptr</code> specify complexity requirements?</p>
809 <b>A.</b> Because complexity requirements limit implementors and complicate the
810 specification without apparent benefit to <code>shared_ptr</code> users. For example,
811 error-checking implementations might become non-conforming if they had to meet
812 stringent complexity requirements.
814 <p><b>Q.</b> Why doesn't <code>shared_ptr</code> provide a <code>release()</code> function?</p>
816 <b>A.</b> <code>shared_ptr</code> cannot give away ownership unless it's <code>unique()</code>
817 because the other copy will still destroy the object.</p>
819 <blockquote><pre>shared_ptr<int> a(new int);
820 shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2
822 int * p = a.release();
824 // Who owns p now? b will still call delete on it in its destructor.</pre>
826 <p>Furthermore, the pointer returned by <code>release()</code> would be difficult
827 to deallocate reliably, as the source <code>shared_ptr</code> could have been created
828 with a custom deleter.
830 <p><b>Q.</b> Why is <code>operator->()</code> const, but its return value is a
831 non-const pointer to the element type?</p>
833 <b>A.</b> Shallow copy pointers, including raw pointers, typically don't
834 propagate constness. It makes little sense for them to do so, as you can always
835 obtain a non-const pointer from a const one and then proceed to modify the
836 object through it. <code>shared_ptr</code> is "as close to raw pointers as possible
841 <p><small>Copyright 1999 Greg Colvin and Beman Dawes. Copyright 2002 Darin Adler.
842 Copyright 2002-2005, 2012, 2013 Peter Dimov. Distributed under the Boost Software License,
843 Version 1.0. See accompanying file <a href="../../LICENSE_1_0.txt">LICENSE_1_0.txt</a>
844 or copy at <a href="http://www.boost.org/LICENSE_1_0.txt">http://www.boost.org/LICENSE_1_0.txt</a>.</small></p>