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">
8 <h1><A href="../../index.htm"><IMG height="86" alt="boost.png (6897 bytes)" src="../../boost.png" width="277" align="middle"
9 border="0"></A>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="#Handle/Body">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><a name="Introduction">Introduction</a></h2>
22 <p>The <b>shared_ptr</b> 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 <b>shared_ptr</b> pointing to it is
25 destroyed or reset. See the <A href="#example">example</A>.</p>
26 <p>Every <b>shared_ptr</b> meets the <b>CopyConstructible</b> and <b>Assignable</b>
27 requirements of the C++ Standard Library, and so can be used in standard
28 library containers. Comparison operators are supplied so that <b>shared_ptr</b>
29 works with the standard library's associative containers.</p>
30 <p>Normally, a <b>shared_ptr</b> cannot correctly hold a pointer to a dynamically
31 allocated array. See <A href="shared_array.htm"><b>shared_array</b></A> for
33 <p>Because the implementation uses reference counting, cycles of <b>shared_ptr</b> instances
34 will not be reclaimed. For example, if <b>main()</b> holds a <b>shared_ptr</b> to
35 <b>A</b>, which directly or indirectly holds a <b>shared_ptr</b> back to <b>A</b>,
36 <b>A</b>'s use count will be 2. Destruction of the original <b>shared_ptr</b> will
37 leave <b>A</b> dangling with a use count of 1. Use <A href="weak_ptr.htm">weak_ptr</A>
38 to "break cycles."</p>
39 <p>The class template is parameterized on <b>T</b>, the type of the object pointed
40 to. <STRONG>shared_ptr</STRONG> and most of its member functions place no
41 requirements on <STRONG>T</STRONG>; it is allowed to be an incomplete type, or <STRONG>
42 void</STRONG>. Member functions that do place additional requirements (<A href="#constructors">constructors</A>,
43 <A href="#reset">reset</A>) are explicitly documented below.</p>
44 <P><STRONG>shared_ptr<T></STRONG> can be implicitly converted to <STRONG>shared_ptr<U></STRONG>
45 whenever <STRONG>T*</STRONG> can be implicitly converted to <STRONG>U*</STRONG>.
46 In particular, <STRONG>shared_ptr<T></STRONG> is implicitly convertible
47 to <STRONG>shared_ptr<T const></STRONG>, to <STRONG>shared_ptr<U></STRONG>
48 where <STRONG>U</STRONG> is an accessible base of <STRONG>T</STRONG>, and to <STRONG>
49 shared_ptr<void></STRONG>.</P>
50 <P><STRONG>shared_ptr</STRONG> is now part of <STRONG>TR1</STRONG>, the first C++
51 Library Technical Report. The latest draft of <STRONG>TR1</STRONG> is available
52 at the following location:</P>
53 <P><A href="http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1745.pdf">http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1745.pdf</A>
55 <P>This implementation conforms to the TR1 specification, with the only exception
56 that it resides in namespace <code>boost</code> instead of <code>std::tr1</code>.</P>
57 <h2><a name="BestPractices">Best Practices</a></h2>
58 <P>A simple guideline that nearly eliminates the possibility of memory leaks is:
59 always use a named smart pointer variable to hold the result of <STRONG>new. </STRONG>
60 Every occurence of the <STRONG>new</STRONG> keyword in the code should have the
62 <PRE>shared_ptr<T> p(new Y);</PRE>
63 <P>It is, of course, acceptable to use another smart pointer in place of <STRONG>shared_ptr</STRONG>
64 above; having <STRONG>T</STRONG> and <STRONG>Y</STRONG> be the same type, or
65 passing arguments to <STRONG>Y</STRONG>'s constructor is also OK.</P>
66 <P>If you observe this guideline, it naturally follows that you will have no
67 explicit <STRONG>delete</STRONG>s; <STRONG>try/catch</STRONG> constructs will
69 <P>Avoid using unnamed <STRONG>shared_ptr</STRONG> temporaries to save typing; to
70 see why this is dangerous, consider this example:</P>
71 <PRE>void f(shared_ptr<int>, int);
76 shared_ptr<int> p(new int(2));
82 f(shared_ptr<int>(new int(2)), g());
85 <P>The function <STRONG>ok</STRONG> follows the guideline to the letter, whereas <STRONG>
86 bad</STRONG> constructs the temporary <STRONG>shared_ptr</STRONG> in place,
87 admitting the possibility of a memory leak. Since function arguments are
88 evaluated in unspecified order, it is possible for <STRONG>new int(2)</STRONG> to
89 be evaluated first, <STRONG>g()</STRONG> second, and we may never get to the <STRONG>
90 shared_ptr </STRONG>constructor if <STRONG>g</STRONG> throws an exception.
91 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">
92 here</A>) of the issue for more information.</P>
93 <P>The exception safety problem described above may also be eliminated by using
94 the <a href="make_shared.html"><code>make_shared</code></a>
95 or <a href="make_shared.html"><code>allocate_shared</code></a>
96 factory functions defined in boost/make_shared.hpp. These factory functions also provide
97 an efficiency benefit by consolidating allocations.<P>
98 <h2><a name="Synopsis">Synopsis</a></h2>
99 <pre>namespace boost {
101 class bad_weak_ptr: public std::exception;
103 template<class T> class <A href="weak_ptr.htm" >weak_ptr</A>;
105 template<class T> class shared_ptr {
109 typedef T <A href="#element_type" >element_type</A>;
111 <A href="#constructors" >shared_ptr</A>(); // never throws
112 template<class Y> explicit <A href="#constructors" >shared_ptr</A>(Y * p);
113 template<class Y, class D> <A href="#constructors" >shared_ptr</A>(Y * p, D d);
114 template<class Y, class D, class A> <A href="#allocator_constructor" >shared_ptr</A>(Y * p, D d, A a);
115 <A href="#destructor" >~shared_ptr</A>(); // never throws
117 <A href="#constructors" >shared_ptr</A>(shared_ptr const & r); // never throws
118 template<class Y> <A href="#constructors" >shared_ptr</A>(shared_ptr<Y> const & r); // never throws
119 template<class Y> <A href="#constructors" >shared_ptr</A>(shared_ptr<Y> const & r, T * p); // never throws
120 template<class Y> explicit <A href="#constructors" >shared_ptr</A>(<A href="weak_ptr.htm" >weak_ptr</A><Y> const & r);
121 template<class Y> explicit <A href="#constructors" >shared_ptr</A>(std::auto_ptr<Y> & r);
123 shared_ptr & <A href="#assignment" >operator=</A>(shared_ptr const & r); // never throws
124 template<class Y> shared_ptr & <A href="#assignment" >operator=</A>(shared_ptr<Y> const & r); // never throws
125 template<class Y> shared_ptr & <A href="#assignment" >operator=</A>(std::auto_ptr<Y> & r);
127 void <A href="#reset" >reset</A>(); // never throws
128 template<class Y> void <A href="#reset" >reset</A>(Y * p);
129 template<class Y, class D> void <A href="#reset" >reset</A>(Y * p, D d);
130 template<class Y, class D, class A> void <A href="#reset" >reset</A>(Y * p, D d, A a);
131 template<class Y> void <A href="#reset" >reset</A>(shared_ptr<Y> const & r, T * p); // never throws
133 T & <A href="#indirection" >operator*</A>() const; // never throws
134 T * <A href="#indirection" >operator-></A>() const; // never throws
135 T * <A href="#get" >get</A>() const; // never throws
137 bool <A href="#unique" >unique</A>() const; // never throws
138 long <A href="#use_count" >use_count</A>() const; // never throws
140 operator <A href="#conversions" ><i>unspecified-bool-type</i></A>() const; // never throws
142 void <A href="#swap" >swap</A>(shared_ptr & b); // never throws
145 template<class T, class U>
146 bool <A href="#comparison" >operator==</A>(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws
148 template<class T, class U>
149 bool <A href="#comparison" >operator!=</A>(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws
151 template<class T, class U>
152 bool <A href="#comparison" >operator<</A>(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws
154 template<class T> void <A href="#free-swap" >swap</A>(shared_ptr<T> & a, shared_ptr<T> & b); // never throws
156 template<class T> T * <A href="#get_pointer" >get_pointer</A>(shared_ptr<T> const & p); // never throws
158 template<class T, class U>
159 shared_ptr<T> <A href="#static_pointer_cast" >static_pointer_cast</A>(shared_ptr<U> const & r); // never throws
161 template<class T, class U>
162 shared_ptr<T> <A href="#const_pointer_cast" >const_pointer_cast</A>(shared_ptr<U> const & r); // never throws
164 template<class T, class U>
165 shared_ptr<T> <A href="#dynamic_pointer_cast" >dynamic_pointer_cast</A>(shared_ptr<U> const & r); // never throws
167 template<class E, class T, class Y>
168 std::basic_ostream<E, T> & <A href="#insertion-operator" >operator<<</A> (std::basic_ostream<E, T> & os, shared_ptr<Y> const & p);
170 template<class D, class T>
171 D * <A href="#get_deleter">get_deleter</A>(shared_ptr<T> const & p);
173 <h2><a name="Members">Members</a></h2>
174 <h3><a name="element_type">element_type</a></h3>
175 <pre>typedef T element_type;</pre>
177 <p>Provides the type of the template parameter T.</p>
179 <h3><a name="constructors">constructors</a></h3>
180 <pre>shared_ptr(); // never throws</pre>
182 <p><b>Effects:</b> Constructs an <EM>empty</EM> <b>shared_ptr</b>.</p>
183 <p><b>Postconditions:</b> <code>use_count() == 0 && get() == 0</code>.</p>
184 <p><b>Throws:</b> nothing.</p>
186 <P><EM>[The nothrow guarantee is important, since <STRONG>reset()</STRONG> is specified
187 in terms of the default constructor; this implies that the constructor must not
188 allocate memory.]</EM></P>
189 <pre>template<class Y> explicit shared_ptr(Y * p);</pre>
191 <p><b>Requirements:</b> <b>p</b> must be convertible to <b>T *</b>. <STRONG>Y</STRONG>
192 must be a complete type. The expression <code>delete p</code> must be
193 well-formed, must not invoke undefined behavior, and must not throw exceptions.
195 <p><b>Effects:</b> Constructs a <b>shared_ptr</b> that <EM>owns</EM> the pointer <b>p</b>.</p>
196 <p><b>Postconditions:</b> <code>use_count() == 1 && get() == p</code>.</p>
197 <p><b>Throws:</b> <STRONG>std::bad_alloc</STRONG>, or an implementation-defined
198 exception when a resource other than memory could not be obtained.</p>
199 <p><b>Exception safety:</b> If an exception is thrown, <code>delete p</code> is
201 <P><STRONG>Notes:</STRONG> <B>p</B> must be a pointer to an object that was
202 allocated via a C++ <B>new</B> expression or be 0. The postcondition that <A href="#use_count">
203 use count</A> is 1 holds even if <b>p</b> is 0; invoking <STRONG>delete</STRONG>
204 on a pointer that has a value of 0 is harmless.</P>
206 <P><EM>[This constructor has been changed to a template in order to remember the actual
207 pointer type passed. The destructor will call <STRONG>delete</STRONG> with the
208 same pointer, complete with its original type, even when <STRONG>T</STRONG> does
209 not have a virtual destructor, or is <STRONG>void</STRONG>.</EM></P>
210 <P><EM>The optional intrusive counting support has been dropped as it exposes too much
211 implementation details and doesn't interact well with <STRONG>weak_ptr</STRONG>.
212 The current implementation uses a different mechanism, <A href="enable_shared_from_this.html">
213 enable_shared_from_this</A>, to solve the "<STRONG>shared_ptr</STRONG> from <STRONG>
214 this</STRONG>" problem.</EM><EM>]</EM></P>
215 <a name="allocator_constructor"></a>
216 <pre>template<class Y, class D> shared_ptr(Y * p, D d);
217 template<class Y, class D, class A> shared_ptr(Y * p, D d, A a);</pre>
219 <p><b>Requirements:</b> <B>p</B> must be convertible to <B>T *</B>. <STRONG>D</STRONG>
220 must be <STRONG>CopyConstructible</STRONG>. The copy constructor and destructor
221 of <b>D</b> must not throw. The expression <code>d(p)</code> must be
222 well-formed, must not invoke undefined behavior, and must not throw exceptions. <STRONG>
223 A</STRONG> must be an <EM>Allocator</EM>, as described in section 20.1.5 (<STRONG>Allocator
224 requirements</STRONG>) of the C++ Standard.
226 <p><b>Effects:</b> Constructs a <b>shared_ptr</b> that <EM>owns</EM> the pointer <STRONG>
227 p</STRONG> and the deleter <b>d</b>. The second constructor allocates
228 memory using a copy of <STRONG>a</STRONG>.</p>
229 <p><b>Postconditions:</b> <code>use_count() == 1 && get() == p</code>.</p>
230 <p><b>Throws:</b> <STRONG>std::bad_alloc</STRONG>, or an implementation-defined
231 exception when a resource other than memory could not be obtained.</p>
232 <p><b>Exception safety:</b> If an exception is thrown, <code>d(p)</code> is called.</p>
233 <p><b>Notes:</b> When the the time comes to delete the object pointed to by <b>p</b>,
234 the stored copy of <STRONG>d</STRONG> is invoked with the stored copy of <STRONG>p</STRONG>
237 <P><EM>[Custom deallocators allow a factory function returning a <STRONG>shared_ptr</STRONG>
238 to insulate the user from its memory allocation strategy. Since the deallocator
239 is not part of the type, changing the allocation strategy does not break source
240 or binary compatibility, and does not require a client recompilation. For
241 example, a "no-op" deallocator is useful when returning a <STRONG>shared_ptr</STRONG>
242 to a statically allocated object, and other variations allow a <STRONG>shared_ptr</STRONG>
243 to be used as a wrapper for another smart pointer, easing interoperability.</EM></P>
244 <P><EM>The support for custom deallocators does not impose significant overhead. Other <STRONG>
245 shared_ptr</STRONG> features still require a deallocator to be kept.</EM></P>
246 <P><EM>The requirement that the copy constructor of <b>D</b> does not throw comes from
247 the pass by value. If the copy constructor throws, the pointer is leaked.
248 Removing the requirement requires a pass by (const) reference.</EM></P>
249 <P><EM>The main problem with pass by reference lies in its interaction with rvalues. A
250 const reference may still cause a copy, and will require a const operator(). A
251 non-const reference won't bind to an rvalue at all. A good solution to this
252 problem is the rvalue reference proposed in <A href="http://std.dkuug.dk/jtc1/sc22/wg21/docs/papers/2002/n1377.htm">
253 N1377</A>/<A href="http://std.dkuug.dk/jtc1/sc22/wg21/docs/papers/2002/n1385.htm">N1385</A>.]</EM></P>
254 <pre>shared_ptr(shared_ptr const & r); // never throws
255 template<class Y> shared_ptr(shared_ptr<Y> const & r); // never throws</pre>
257 <p><b>Effects:</b> If <b>r</b> is <EM>empty</EM>, constructs an <EM>empty</EM> <b>shared_ptr</b>;
258 otherwise, constructs a <b>shared_ptr</b> that <EM>shares ownership</EM> with <b>r</b>.</p>
259 <p><b>Postconditions:</b> <code>get() == r.get() && use_count() ==
260 r.use_count()</code>.</p>
261 <p><b>Throws:</b> nothing.</p>
263 <pre>template<class Y> shared_ptr(shared_ptr<Y> const & r, T * p); // never throws</pre>
265 <p><b>Effects:</b> constructs a <b>shared_ptr</b> that <EM>shares ownership</EM> with
266 <b>r</b> and stores <b>p</b>.</p>
267 <p><b>Postconditions:</b> <code>get() == p && use_count() == r.use_count()</code>.</p>
268 <p><b>Throws:</b> nothing.</p>
270 <pre>template<class Y> explicit shared_ptr(<A href="weak_ptr.htm" >weak_ptr</A><Y> const & r);</pre>
272 <p><b>Effects:</b> Constructs a <b>shared_ptr</b> that <EM>shares ownership</EM> with
273 <b>r</b> and stores a copy of the pointer stored in <STRONG>r</STRONG>.</p>
274 <p><b>Postconditions:</b> <code>use_count() == r.use_count()</code>.</p>
275 <p><b>Throws:</b> <b>bad_weak_ptr</b> when <code>r.use_count() == 0</code>.</p>
276 <p><b>Exception safety:</b> If an exception is thrown, the constructor has no
279 <pre>template<class Y> shared_ptr(std::auto_ptr<Y> & r);</pre>
281 <P><B>Effects:</B> Constructs a <B>shared_ptr</B>, as if by storing a copy of <STRONG>r.release()</STRONG>.</P>
282 <p><b>Postconditions:</b> <code>use_count() == 1</code>.</p>
283 <p><b>Throws:</b> <STRONG>std::bad_alloc</STRONG>, or an implementation-defined
284 exception when a resource other than memory could not be obtained.</p>
285 <P><B>Exception safety:</B> If an exception is thrown, the constructor has no
288 <P><EM>[This constructor takes a the source <STRONG>auto_ptr</STRONG> by reference and
289 not by value, and cannot accept <STRONG>auto_ptr</STRONG> temporaries. This is
290 by design, as the constructor offers the strong guarantee; an rvalue reference
291 would solve this problem, too.]</EM></P>
292 <h3><a name="destructor">destructor</a></h3>
293 <pre>~shared_ptr(); // never throws</pre>
295 <P><B>Effects:</B></P>
298 If <STRONG>*this</STRONG> is <EM>empty</EM>, or <EM>shares ownership</EM> with
299 another <STRONG>shared_ptr</STRONG> instance (<code>use_count() > 1</code>),
300 there are no side effects.
302 Otherwise, if <STRONG>*this</STRONG> <EM>owns</EM> a pointer <STRONG>p</STRONG>
303 and a deleter <STRONG>d</STRONG>, <code>d(p)</code>
306 Otherwise, <STRONG>*this</STRONG> <EM>owns</EM> a pointer <STRONG>p</STRONG>,
307 and <code>delete p</code> is called.</LI></UL>
308 <P><B>Throws:</B> nothing.</P>
310 <H3><a name="assignment">assignment</a></H3>
311 <pre>shared_ptr & operator=(shared_ptr const & r); // never throws
312 template<class Y> shared_ptr & operator=(shared_ptr<Y> const & r); // never throws
313 template<class Y> shared_ptr & operator=(std::auto_ptr<Y> & r);</pre>
315 <P><B>Effects:</B> Equivalent to <code>shared_ptr(r).swap(*this)</code>.</P>
316 <P><B>Returns:</B> <code>*this</code>.</P>
317 <P><B>Notes:</B> The use count updates caused by the temporary object construction
318 and destruction are not considered observable side effects, and the
319 implementation is free to meet the effects (and the implied guarantees) via
320 different means, without creating a temporary. In particular, in the example:</P>
321 <pre>shared_ptr<int> p(new int);
322 shared_ptr<void> q(p);
326 <p>both assignments may be no-ops.</p>
328 <h3><a name="reset">reset</a></h3>
329 <pre>void reset(); // never throws</pre>
331 <P><B>Effects:</B> Equivalent to <code>shared_ptr().swap(*this)</code>.</P>
333 <pre>template<class Y> void reset(Y * p);</pre>
335 <P><B>Effects:</B> Equivalent to <code>shared_ptr(p).swap(*this)</code>.</P>
337 <pre>template<class Y, class D> void reset(Y * p, D d);</pre>
339 <P><B>Effects:</B> Equivalent to <code>shared_ptr(p, d).swap(*this)</code>.</P>
341 <pre>template<class Y, class D, class A> void reset(Y * p, D d, A a);</pre>
343 <P><B>Effects:</B> Equivalent to <code>shared_ptr(p, d, a).swap(*this)</code>.</P>
345 <pre>template<class Y> void reset(shared_ptr<Y> const & r, T * p); // never throws</pre>
347 <P><B>Effects:</B> Equivalent to <code>shared_ptr(r, p).swap(*this)</code>.</P>
349 <h3><a name="indirection">indirection</a></h3>
350 <pre>T & operator*() const; // never throws</pre>
352 <p><b>Requirements:</b> The stored pointer must not be 0.</p>
353 <p><b>Returns:</b> a reference to the object pointed to by the stored pointer.</p>
354 <p><b>Throws:</b> nothing.</p>
356 <pre>T * operator->() const; // never throws</pre>
358 <p><b>Requirements:</b> The stored pointer must not be 0.</p>
359 <p><b>Returns:</b> the stored pointer.</p>
360 <p><b>Throws:</b> nothing.</p>
362 <h3><a name="get">get</a></h3>
363 <pre>T * get() const; // never throws</pre>
365 <p><b>Returns:</b> the stored pointer.</p>
366 <p><b>Throws:</b> nothing.</p>
368 <h3><a name="unique">unique</a></h3>
369 <pre>bool unique() const; // never throws</pre>
371 <p><b>Returns:</b> <code>use_count() == 1</code>.</p>
372 <p><b>Throws:</b> nothing.</p>
373 <P><B>Notes:</B> <code>unique()</code> may be faster than <code>use_count()</code>.
374 If you are using <code>unique()</code> to implement copy on write, do not rely
375 on a specific value when the stored pointer is zero.</P>
377 <h3><a name="use_count">use_count</a></h3>
378 <pre>long use_count() const; // never throws</pre>
380 <p><b>Returns:</b> the number of <b>shared_ptr</b> objects, <STRONG>*this</STRONG> included,
381 that <i>share ownership</i> with <b>*this</b>, or 0 when <STRONG>*this</STRONG>
382 is <EM>empty</EM>.</p>
383 <p><b>Throws:</b> nothing.</p>
384 <P><B>Notes:</B> <code>use_count()</code> is not necessarily efficient. Use only
385 for debugging and testing purposes, not for production code.</P>
387 <h3><a name="conversions">conversions</a></h3>
388 <pre>operator <i>unspecified-bool-type</i> () const; // never throws</pre>
390 <p><b>Returns:</b> an unspecified value that, when used in boolean contexts, is
391 equivalent to <code>get() != 0</code>.</p>
392 <p><b>Throws:</b> nothing.</p>
393 <P><B>Notes:</B> This conversion operator allows <b>shared_ptr</b> objects to be
394 used in boolean contexts, like <code>if (p && p->valid()) {}</code>.
395 The actual target type is typically a pointer to a member function, avoiding
396 many of the implicit conversion pitfalls.</P>
398 <P><EM>[The conversion to bool is not merely syntactic sugar. It allows <STRONG>shared_ptr</STRONG>s
399 to be declared in conditions when using <A href="#dynamic_pointer_cast">dynamic_pointer_cast</A>
400 or <A href="weak_ptr.htm#lock">weak_ptr::lock</A>.]</EM></P>
401 <h3><a name="swap">swap</a></h3>
402 <pre>void swap(shared_ptr & b); // never throws</pre>
404 <p><b>Effects:</b> Exchanges the contents of the two smart pointers.</p>
405 <p><b>Throws:</b> nothing.</p>
407 <h2><a name="functions">Free Functions</a></h2>
408 <h3><a name="comparison">comparison</a></h3>
409 <pre>template<class T, class U>
410 bool operator==(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws</pre>
412 <p><b>Returns:</b> <code>a.get() == b.get()</code>.</p>
413 <p><b>Throws:</b> nothing.</p>
415 <pre>template<class T, class U>
416 bool operator!=(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws</pre>
418 <p><b>Returns:</b> <code>a.get() != b.get()</code>.</p>
419 <p><b>Throws:</b> nothing.</p>
421 <pre>template<class T, class U>
422 bool operator<(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws</pre>
424 <p><b>Returns:</b> an unspecified value such that</p>
427 <b>operator<</b> is a strict weak ordering as described in section 25.3 <code>[lib.alg.sorting]</code>
430 under the equivalence relation defined by <STRONG>operator<</STRONG>, <code>!(a
431 < b) && !(b < a)</code>, two <STRONG>shared_ptr</STRONG> instances
432 are equivalent if and only if they <EM>share ownership</EM> or are both <EM>empty</EM>.</LI></UL>
433 <p><b>Throws:</b> nothing.</p>
434 <P><B>Notes:</B> Allows <STRONG>shared_ptr</STRONG> objects to be used as keys in
435 associative containers.</P>
437 <P><EM>[<STRONG>Operator<</STRONG> has been preferred over a <STRONG>std::less </STRONG>
438 specialization for consistency and legality reasons, as <STRONG>std::less</STRONG>
439 is required to return the results of <STRONG>operator<</STRONG>, and many
440 standard algorithms use <STRONG>operator<</STRONG> instead of <STRONG>std::less</STRONG>
441 for comparisons when a predicate is not supplied. Composite objects, like <STRONG>std::pair</STRONG>,
442 also implement their <STRONG>operator<</STRONG> in terms of their contained
443 subobjects' <STRONG>operator<</STRONG>.</EM></P>
444 <P><EM>The rest of the comparison operators are omitted by design.]</EM></P>
445 <h3><a name="free-swap">swap</a></h3>
446 <pre>template<class T>
447 void swap(shared_ptr<T> & a, shared_ptr<T> & b); // never throws</pre>
449 <P><B>Effects:</B> Equivalent to <code>a.swap(b)</code>.</P>
450 <P><B>Throws:</B> nothing.</P>
451 <P><B>Notes:</B> Matches the interface of <B>std::swap</B>. Provided as an aid to
452 generic programming.</P>
454 <P><EM>[<STRONG>swap</STRONG> is defined in the same namespace as <STRONG>shared_ptr</STRONG>
455 as this is currently the only legal way to supply a <STRONG>swap</STRONG> function
456 that has a chance to be used by the standard library.]</EM></P>
457 <h3><a name="get_pointer">get_pointer</a></h3>
458 <pre>template<class T>
459 T * get_pointer(shared_ptr<T> const & p); // never throws</pre>
461 <P><B>Returns:</B> <code>p.get()</code>.</P>
462 <P><B>Throws:</B> nothing.</P>
463 <P><B>Notes:</B> Provided as an aid to generic programming. Used by <A href="../bind/mem_fn.html">
466 <h3><a name="static_pointer_cast">static_pointer_cast</a></h3>
467 <pre>template<class T, class U>
468 shared_ptr<T> static_pointer_cast(shared_ptr<U> const & r); // never throws</pre>
470 <P><STRONG>Requires:</STRONG> The expression <code>static_cast<T*>(r.get())</code>
471 must be well-formed.</P>
472 <P><B>Returns:</B> If <b>r</b> is <i>empty</i>, an <i>empty</i> <b>shared_ptr<T></b>;
473 otherwise, a <STRONG>shared_ptr<T></STRONG> object that stores a copy of <code>
474 static_cast<T*>(r.get())</code> and <i>shares ownership</i> with <b>r</b>.</P>
475 <P><B>Throws:</B> nothing.</P>
476 <P><B>Notes:</B> the seemingly equivalent expression</P>
477 <p><code>shared_ptr<T>(static_cast<T*>(r.get()))</code></p>
478 <p>will eventually result in undefined behavior, attempting to delete the same
481 <h3><a name="const_pointer_cast">const_pointer_cast</a></h3>
482 <pre>template<class T, class U>
483 shared_ptr<T> const_pointer_cast(shared_ptr<U> const & r); // never throws</pre>
485 <P><STRONG>Requires:</STRONG> The expression <code>const_cast<T*>(r.get())</code>
486 must be well-formed.</P>
487 <P><B>Returns:</B> If <b>r</b> is <i>empty</i>, an <i>empty</i> <b>shared_ptr<T></b>;
488 otherwise, a <STRONG>shared_ptr<T></STRONG> object that stores a copy of <code>
489 const_cast<T*>(r.get())</code> and <i>shares ownership</i> with <b>r</b>.</P>
490 <P><B>Throws:</B> nothing.</P>
491 <P><B>Notes:</B> the seemingly equivalent expression</P>
492 <p><code>shared_ptr<T>(const_cast<T*>(r.get()))</code></p>
493 <p>will eventually result in undefined behavior, attempting to delete the same
496 <h3><a name="dynamic_pointer_cast">dynamic_pointer_cast</a></h3>
497 <pre>template<class T, class U>
498 shared_ptr<T> dynamic_pointer_cast(shared_ptr<U> const & r);</pre>
500 <P><STRONG>Requires:</STRONG> The expression <CODE>dynamic_cast<T*>(r.get())</CODE>
501 must be well-formed and its behavior defined.</P>
502 <P><B>Returns:</B></P>
505 When <CODE>dynamic_cast<T*>(r.get())</CODE> returns a nonzero value, a <STRONG>
506 shared_ptr<T></STRONG> object that stores a copy of it and <i>shares
507 ownership</i> with <STRONG>r</STRONG>;
509 Otherwise, an <i>empty</i> <STRONG>shared_ptr<T></STRONG> object.</LI></UL>
510 <P><B>Throws:</B> nothing.</P>
511 <P><B>Notes:</B> the seemingly equivalent expression</P>
512 <P><CODE>shared_ptr<T>(dynamic_cast<T*>(r.get()))</CODE></P>
513 <P>will eventually result in undefined behavior, attempting to delete the same
516 <h3><a name="insertion-operator">operator<<</a></h3>
517 <pre>template<class E, class T, class Y>
518 std::basic_ostream<E, T> & operator<< (std::basic_ostream<E, T> & os, shared_ptr<Y> const & p);</pre>
520 <p><STRONG>Effects:</STRONG> <code>os << p.get();</code>.</p>
521 <P><B>Returns:</B> <b>os</b>.</P>
523 <h3><a name="get_deleter">get_deleter</a></h3>
524 <pre>template<class D, class T>
525 D * get_deleter(shared_ptr<T> const & p);</pre>
527 <P><B>Returns:</B> If <STRONG>*this</STRONG> <EM>owns</EM> a deleter <STRONG>d</STRONG>
528 of type (cv-unqualified) <STRONG>D</STRONG>, returns <code>&d</code>;
529 otherwise returns 0.</P>
530 <P><B>Throws:</B> nothing.</P>
532 <h2><a name="example">Example</a></h2>
533 <p>See <A href="example/shared_ptr_example.cpp">shared_ptr_example.cpp</A> for a
534 complete example program. The program builds a <b>std::vector</b> and <b>std::set</b>
535 of <b>shared_ptr</b> objects.</p>
536 <p>Note that after the containers have been populated, some of the <b>shared_ptr</b>
537 objects will have a use count of 1 rather than a use count of 2, since the set
538 is a <b>std::set</b> rather than a <b>std::multiset</b>, and thus does not
539 contain duplicate entries. Furthermore, the use count may be even higher at
540 various times while <b>push_back</b> and <b>insert</b> container operations are
541 performed. More complicated yet, the container operations may throw exceptions
542 under a variety of circumstances. Getting the memory management and exception
543 handling in this example right without a smart pointer would be a nightmare.</p>
544 <h2><a name="Handle/Body">Handle/Body</a> Idiom</h2>
545 <p>One common usage of <b>shared_ptr</b> is to implement a handle/body (also called
546 pimpl) idiom which avoids exposing the body (implementation) in the header
548 <p>The <A href="example/shared_ptr_example2_test.cpp">shared_ptr_example2_test.cpp</A>
549 sample program includes a header file, <A href="example/shared_ptr_example2.hpp">shared_ptr_example2.hpp</A>,
550 which uses a <b>shared_ptr<></b> to an incomplete type to hide the
551 implementation. The instantiation of member functions which require a complete
552 type occurs in the <A href="example/shared_ptr_example2.cpp">shared_ptr_example2.cpp</A>
553 implementation file. Note that there is no need for an explicit destructor.
554 Unlike ~scoped_ptr, ~shared_ptr does not require that <b>T</b> be a complete
556 <h2><a name="ThreadSafety">Thread Safety</a></h2>
557 <p><STRONG>shared_ptr</STRONG> objects offer the same level of thread safety as
558 built-in types. A <STRONG>shared_ptr</STRONG> instance can be "read" (accessed
559 using only const operations) simultaneously by multiple threads. Different <STRONG>shared_ptr</STRONG>
560 instances can be "written to" (accessed using mutable operations such as <STRONG>operator=
561 </STRONG>or <STRONG>reset</STRONG>) simultaneosly by multiple threads (even
562 when these instances are copies, and share the same reference count
564 <P>Any other simultaneous accesses result in undefined behavior.</P>
566 <pre>shared_ptr<int> p(new int(42));
571 shared_ptr<int> p2(p); // reads p
574 shared_ptr<int> p3(p); // OK, multiple reads are safe
579 p.reset(new int(1912)); // writes p
582 p2.reset(); // OK, writes p2
587 p = p3; // reads p3, writes p
590 p3.reset(); // writes p3; undefined, simultaneous read/write
595 p3 = p2; // reads p2, writes p3
598 // p2 goes out of scope: undefined, the destructor is considered a "write access"
603 p3.reset(new int(1));
606 p3.reset(new int(2)); // undefined, multiple writes
609 <P>Starting with Boost release 1.33.0, <STRONG>shared_ptr</STRONG> uses a lock-free
610 implementation on the following platforms:</P>
613 GNU GCC on x86 or x86-64;
617 Metrowerks CodeWarrior on PowerPC;
622 <P>If your program is single-threaded and does not link to any libraries that might
623 have used <STRONG>shared_ptr</STRONG> in its default configuration, you can <STRONG>
624 #define</STRONG> the macro <STRONG>BOOST_SP_DISABLE_THREADS</STRONG> on a
625 project-wide basis to switch to ordinary non-atomic reference count updates.</P>
626 <P>(Defining <STRONG>BOOST_SP_DISABLE_THREADS</STRONG> in some, but not all,
627 translation units is technically a violation of the One Definition Rule and
628 undefined behavior. Nevertheless, the implementation attempts to do its best to
629 accommodate the request to use non-atomic updates in those translation units.
630 No guarantees, though.)</P>
631 <P>You can define the macro <STRONG>BOOST_SP_USE_PTHREADS</STRONG> to turn off the
632 lock-free platform-specific implementation and fall back to the generic <STRONG>pthread_mutex_t</STRONG>-based
634 <h2><a name="FAQ">Frequently Asked Questions</a></h2>
635 <P><B>Q.</B> There are several variations of shared pointers, with different
636 tradeoffs; why does the smart pointer library supply only a single
637 implementation? It would be useful to be able to experiment with each type so
638 as to find the most suitable for the job at hand?</P>
640 <b>A.</b> An important goal of <STRONG>shared_ptr</STRONG> is to provide a
641 standard shared-ownership pointer. Having a single pointer type is important
642 for stable library interfaces, since different shared pointers typically cannot
643 interoperate, i.e. a reference counted pointer (used by library A) cannot share
644 ownership with a linked pointer (used by library B.)<BR>
646 <P><B>Q.</B> Why doesn't <B>shared_ptr</B> have template parameters supplying
647 traits or policies to allow extensive user customization?</P>
649 <B>A.</B> Parameterization discourages users. The <B>shared_ptr</B> template is
650 carefully crafted to meet common needs without extensive parameterization. Some
651 day a highly configurable smart pointer may be invented that is also very easy
652 to use and very hard to misuse. Until then, <B>shared_ptr</B> is the smart
653 pointer of choice for a wide range of applications. (Those interested in policy
654 based smart pointers should read <A href="http://www.awprofessional.com/bookstore/product.asp?isbn=0201704315&rl=1">
655 Modern C++ Design</A> by Andrei Alexandrescu.)<BR>
657 <P><B>Q.</B> I am not convinced. Default parameters can be used where appropriate
658 to hide the complexity. Again, why not policies?</P>
660 <B>A.</B> Template parameters affect the type. See the answer to the first
663 <P><B>Q.</B> Why doesn't <b>shared_ptr</b> use a linked list implementation?</P>
665 <b>A.</b> A linked list implementation does not offer enough advantages to
666 offset the added cost of an extra pointer. See <A href="smarttests.htm">timings</A>
667 page. In addition, it is expensive to make a linked list implementation thread
670 <P><b>Q.</b> Why doesn't <b>shared_ptr</b> (or any of the other Boost smart
671 pointers) supply an automatic conversion to <b>T*</b>?</P>
673 <b>A.</b> Automatic conversion is believed to be too error prone.<BR>
675 <P><B>Q.</B> Why does <b>shared_ptr</b> supply use_count()?</P>
677 <b>A.</b> As an aid to writing test cases and debugging displays. One of the
678 progenitors had use_count(), and it was useful in tracking down bugs in a
679 complex project that turned out to have cyclic-dependencies.<BR>
681 <P><B>Q.</B> Why doesn't <b>shared_ptr</b> specify complexity requirements?</P>
683 <b>A.</b> Because complexity requirements limit implementors and complicate the
684 specification without apparent benefit to <b>shared_ptr</b> users. For example,
685 error-checking implementations might become non-conforming if they had to meet
686 stringent complexity requirements.<BR>
688 <P><b>Q.</b> Why doesn't <b>shared_ptr</b> provide a release() function?</P>
690 <b>A.</b> <b>shared_ptr</b> cannot give away ownership unless it's unique()
691 because the other copy will still destroy the object.</P>
693 <blockquote><pre>shared_ptr<int> a(new int);
694 shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2
696 int * p = a.release();
698 // Who owns p now? b will still call delete on it in its destructor.</pre>
700 <p>Furthermore, the pointer returned by <code>release()</code> would be difficult
701 to deallocate reliably, as the source <b>shared_ptr</b> could have been created
702 with a custom deleter.<BR>
704 <P><b>Q.</b> Why is <code>operator->()</code> const, but its return value is a
705 non-const pointer to the element type?</P>
707 <b>A.</b> Shallow copy pointers, including raw pointers, typically don't
708 propagate constness. It makes little sense for them to do so, as you can always
709 obtain a non-const pointer from a const one and then proceed to modify the
710 object through it.<b>shared_ptr</b> is "as close to raw pointers as possible
716 $Date: 2009-03-11 08:08:14 -0700 (Wed, 11 Mar 2009) $</p>
717 <p><small>Copyright 1999 Greg Colvin and Beman Dawes. Copyright 2002 Darin Adler.
718 Copyright 2002-2005 Peter Dimov. Distributed under the Boost Software License,
719 Version 1.0. See accompanying file <A href="../../LICENSE_1_0.txt">LICENSE_1_0.txt</A>
720 or copy at <A href="http://www.boost.org/LICENSE_1_0.txt">http://www.boost.org/LICENSE_1_0.txt</A>.</small></p>