OSDN Git Service

2011-05-02 Jonathan Wakely <jwakely.gcc@gmail.com>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / doc / html / manual / memory.html
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml"><head><title>Memory</title><meta name="generator" content="DocBook XSL-NS Stylesheets V1.76.1"/><meta name="keywords" content="&#10;      ISO C++&#10;    , &#10;      library&#10;    "/><link rel="home" href="../spine.html" title="The GNU C++ Library"/><link rel="up" href="utilities.html" title="Chapter 6.  Utilities"/><link rel="prev" href="pairs.html" title="Pairs"/><link rel="next" href="traits.html" title="Traits"/></head><body><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Memory</th></tr><tr><td align="left"><a accesskey="p" href="pairs.html">Prev</a> </td><th width="60%" align="center">Chapter 6. 
4   Utilities
5   
6 </th><td align="right"> <a accesskey="n" href="traits.html">Next</a></td></tr></table><hr/></div><div class="section" title="Memory"><div class="titlepage"><div><div><h2 class="title"><a id="std.util.memory"/>Memory</h2></div></div></div><p>
7     Memory contains three general areas. First, function and operator
8     calls via <code class="function">new</code> and <code class="function">delete</code>
9     operator or member function calls.  Second, allocation via
10     <code class="classname">allocator</code>. And finally, smart pointer and
11     intelligent pointer abstractions.
12   </p><div class="section" title="Allocators"><div class="titlepage"><div><div><h3 class="title"><a id="std.util.memory.allocator"/>Allocators</h3></div></div></div><p>
13  Memory management for Standard Library entities is encapsulated in a
14  class template called <code class="classname">allocator</code>. The
15  <code class="classname">allocator</code> abstraction is used throughout the
16  library in <code class="classname">string</code>, container classes,
17  algorithms, and parts of iostreams. This class, and base classes of
18  it, are the superset of available free store (<span class="quote">“<span class="quote">heap</span>”</span>)
19  management classes.
20 </p><div class="section" title="Requirements"><div class="titlepage"><div><div><h4 class="title"><a id="allocator.req"/>Requirements</h4></div></div></div><p>
21     The C++ standard only gives a few directives in this area:
22   </p><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p>
23        When you add elements to a container, and the container must
24        allocate more memory to hold them, the container makes the
25        request via its <span class="type">Allocator</span> template
26        parameter, which is usually aliased to
27        <span class="type">allocator_type</span>.  This includes adding chars
28        to the string class, which acts as a regular STL container in
29        this respect.
30       </p></li><li class="listitem"><p>
31        The default <span class="type">Allocator</span> argument of every
32        container-of-T is <code class="classname">allocator&lt;T&gt;</code>.
33        </p></li><li class="listitem"><p>
34        The interface of the <code class="classname">allocator&lt;T&gt;</code> class is
35          extremely simple.  It has about 20 public declarations (nested
36          typedefs, member functions, etc), but the two which concern us most
37          are:
38        </p><pre class="programlisting">
39          T*    allocate   (size_type n, const void* hint = 0);
40          void  deallocate (T* p, size_type n);
41        </pre><p>
42          The <code class="varname">n</code> arguments in both those
43          functions is a <span class="emphasis"><em>count</em></span> of the number of
44          <span class="type">T</span>'s to allocate space for, <span class="emphasis"><em>not their
45          total size</em></span>.
46          (This is a simplification; the real signatures use nested typedefs.)
47        </p></li><li class="listitem"><p>
48          The storage is obtained by calling <code class="function">::operator
49          new</code>, but it is unspecified when or how
50          often this function is called.  The use of the
51          <code class="varname">hint</code> is unspecified, but intended as an
52          aid to locality if an implementation so
53          desires. <code class="constant">[20.4.1.1]/6</code>
54        </p></li></ul></div><p>
55      Complete details can be found in the C++ standard, look in
56      <code class="constant">[20.4 Memory]</code>.
57    </p></div><div class="section" title="Design Issues"><div class="titlepage"><div><div><h4 class="title"><a id="allocator.design_issues"/>Design Issues</h4></div></div></div><p>
58     The easiest way of fulfilling the requirements is to call
59     <code class="function">operator new</code> each time a container needs
60     memory, and to call <code class="function">operator delete</code> each time
61     the container releases memory. This method may be <a class="link" href="http://gcc.gnu.org/ml/libstdc++/2001-05/msg00105.html">slower</a>
62     than caching the allocations and re-using previously-allocated
63     memory, but has the advantage of working correctly across a wide
64     variety of hardware and operating systems, including large
65     clusters. The <code class="classname">__gnu_cxx::new_allocator</code>
66     implements the simple operator new and operator delete semantics,
67     while <code class="classname">__gnu_cxx::malloc_allocator</code>
68     implements much the same thing, only with the C language functions
69     <code class="function">std::malloc</code> and <code class="function">free</code>.
70   </p><p>
71     Another approach is to use intelligence within the allocator
72     class to cache allocations. This extra machinery can take a variety
73     of forms: a bitmap index, an index into an exponentially increasing
74     power-of-two-sized buckets, or simpler fixed-size pooling cache.
75     The cache is shared among all the containers in the program: when
76     your program's <code class="classname">std::vector&lt;int&gt;</code> gets
77   cut in half and frees a bunch of its storage, that memory can be
78   reused by the private
79   <code class="classname">std::list&lt;WonkyWidget&gt;</code> brought in from
80   a KDE library that you linked against.  And operators
81   <code class="function">new</code> and <code class="function">delete</code> are not
82   always called to pass the memory on, either, which is a speed
83   bonus. Examples of allocators that use these techniques are
84   <code class="classname">__gnu_cxx::bitmap_allocator</code>,
85   <code class="classname">__gnu_cxx::pool_allocator</code>, and
86   <code class="classname">__gnu_cxx::__mt_alloc</code>.
87   </p><p>
88     Depending on the implementation techniques used, the underlying
89     operating system, and compilation environment, scaling caching
90     allocators can be tricky. In particular, order-of-destruction and
91     order-of-creation for memory pools may be difficult to pin down
92     with certainty, which may create problems when used with plugins
93     or loading and unloading shared objects in memory. As such, using
94     caching allocators on systems that do not support
95     <code class="function">abi::__cxa_atexit</code> is not recommended.
96   </p></div><div class="section" title="Implementation"><div class="titlepage"><div><div><h4 class="title"><a id="allocator.impl"/>Implementation</h4></div></div></div><div class="section" title="Interface Design"><div class="titlepage"><div><div><h5 class="title"><a id="id554726"/>Interface Design</h5></div></div></div><p>
97      The only allocator interface that
98      is supported is the standard C++ interface. As such, all STL
99      containers have been adjusted, and all external allocators have
100      been modified to support this change.
101    </p><p>
102      The class <code class="classname">allocator</code> just has typedef,
103    constructor, and rebind members. It inherits from one of the
104    high-speed extension allocators, covered below. Thus, all
105    allocation and deallocation depends on the base class.
106    </p><p>
107      The base class that <code class="classname">allocator</code> is derived from
108      may not be user-configurable.
109 </p></div><div class="section" title="Selecting Default Allocation Policy"><div class="titlepage"><div><div><h5 class="title"><a id="id554755"/>Selecting Default Allocation Policy</h5></div></div></div><p>
110      It's difficult to pick an allocation strategy that will provide
111    maximum utility, without excessively penalizing some behavior. In
112    fact, it's difficult just deciding which typical actions to measure
113    for speed.
114    </p><p>
115      Three synthetic benchmarks have been created that provide data
116      that is used to compare different C++ allocators. These tests are:
117    </p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
118        Insertion.
119        </p><p>
120        Over multiple iterations, various STL container
121      objects have elements inserted to some maximum amount. A variety
122      of allocators are tested.
123      Test source for <a class="link" href="http://gcc.gnu.org/viewcvs/trunk/libstdc%2B%2B-v3/testsuite/performance/23_containers/insert/sequence.cc?view=markup">sequence</a>
124      and <a class="link" href="http://gcc.gnu.org/viewcvs/trunk/libstdc%2B%2B-v3/testsuite/performance/23_containers/insert/associative.cc?view=markup">associative</a>
125      containers.
126        </p></li><li class="listitem"><p>
127        Insertion and erasure in a multi-threaded environment.
128        </p><p>
129        This test shows the ability of the allocator to reclaim memory
130      on a per-thread basis, as well as measuring thread contention
131      for memory resources.
132      Test source
133     <a class="link" href="http://gcc.gnu.org/viewcvs/trunk/libstdc%2B%2B-v3/testsuite/performance/23_containers/insert_erase/associative.cc?view=markup">here</a>.
134        </p></li><li class="listitem"><p>
135          A threaded producer/consumer model.
136        </p><p>
137        Test source for
138      <a class="link" href="http://gcc.gnu.org/viewcvs/trunk/libstdc++-v3/testsuite/performance/23_containers/producer_consumer/sequence.cc?view=markup">sequence</a>
139      and
140      <a class="link" href="http://gcc.gnu.org/viewcvs/trunk/libstdc++-v3/testsuite/performance/23_containers/producer_consumer/associative.cc?view=markup">associative</a>
141      containers.
142      </p></li></ol></div><p>
143      The current default choice for
144      <code class="classname">allocator</code> is
145      <code class="classname">__gnu_cxx::new_allocator</code>.
146    </p></div><div class="section" title="Disabling Memory Caching"><div class="titlepage"><div><div><h5 class="title"><a id="id554866"/>Disabling Memory Caching</h5></div></div></div><p>
147       In use, <code class="classname">allocator</code> may allocate and
148       deallocate using implementation-specified strategies and
149       heuristics. Because of this, every call to an allocator object's
150       <code class="function">allocate</code> member function may not actually
151       call the global operator new. This situation is also duplicated
152       for calls to the <code class="function">deallocate</code> member
153       function.
154     </p><p>
155      This can be confusing.
156    </p><p>
157      In particular, this can make debugging memory errors more
158      difficult, especially when using third party tools like valgrind or
159      debug versions of <code class="function">new</code>.
160    </p><p>
161      There are various ways to solve this problem. One would be to use
162      a custom allocator that just called operators
163      <code class="function">new</code> and <code class="function">delete</code>
164      directly, for every allocation. (See
165      <code class="filename">include/ext/new_allocator.h</code>, for instance.)
166      However, that option would involve changing source code to use
167      a non-default allocator. Another option is to force the
168      default allocator to remove caching and pools, and to directly
169      allocate with every call of <code class="function">allocate</code> and
170      directly deallocate with every call of
171      <code class="function">deallocate</code>, regardless of efficiency. As it
172      turns out, this last option is also available.
173    </p><p>
174      To globally disable memory caching within the library for the
175      default allocator, merely set
176      <code class="constant">GLIBCXX_FORCE_NEW</code> (with any value) in the
177      system's environment before running the program. If your program
178      crashes with <code class="constant">GLIBCXX_FORCE_NEW</code> in the
179      environment, it likely means that you linked against objects
180      built against the older library (objects which might still using the
181      cached allocations...).
182   </p></div></div><div class="section" title="Using a Specific Allocator"><div class="titlepage"><div><div><h4 class="title"><a id="allocator.using"/>Using a Specific Allocator</h4></div></div></div><p>
183      You can specify different memory management schemes on a
184      per-container basis, by overriding the default
185      <span class="type">Allocator</span> template parameter.  For example, an easy
186       (but non-portable) method of specifying that only <code class="function">malloc</code> or <code class="function">free</code>
187       should be used instead of the default node allocator is:
188    </p><pre class="programlisting">
189     std::list &lt;int, __gnu_cxx::malloc_allocator&lt;int&gt; &gt;  malloc_list;</pre><p>
190       Likewise, a debugging form of whichever allocator is currently in use:
191     </p><pre class="programlisting">
192     std::deque &lt;int, __gnu_cxx::debug_allocator&lt;std::allocator&lt;int&gt; &gt; &gt;  debug_deque;
193       </pre></div><div class="section" title="Custom Allocators"><div class="titlepage"><div><div><h4 class="title"><a id="allocator.custom"/>Custom Allocators</h4></div></div></div><p>
194     Writing a portable C++ allocator would dictate that the interface
195     would look much like the one specified for
196     <code class="classname">allocator</code>. Additional member functions, but
197     not subtractions, would be permissible.
198   </p><p>
199      Probably the best place to start would be to copy one of the
200    extension allocators: say a simple one like
201    <code class="classname">new_allocator</code>.
202    </p></div><div class="section" title="Extension Allocators"><div class="titlepage"><div><div><h4 class="title"><a id="allocator.ext"/>Extension Allocators</h4></div></div></div><p>
203     Several other allocators are provided as part of this
204     implementation.  The location of the extension allocators and their
205     names have changed, but in all cases, functionality is
206     equivalent. Starting with gcc-3.4, all extension allocators are
207     standard style. Before this point, SGI style was the norm. Because of
208     this, the number of template arguments also changed. Here's a simple
209     chart to track the changes.
210   </p><p>
211     More details on each of these extension allocators follows.
212   </p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
213        <code class="classname">new_allocator</code>
214        </p><p>
215          Simply wraps <code class="function">::operator new</code>
216          and <code class="function">::operator delete</code>.
217        </p></li><li class="listitem"><p>
218        <code class="classname">malloc_allocator</code>
219        </p><p>
220          Simply wraps <code class="function">malloc</code> and
221          <code class="function">free</code>. There is also a hook for an
222          out-of-memory handler (for
223          <code class="function">new</code>/<code class="function">delete</code> this is
224          taken care of elsewhere).
225        </p></li><li class="listitem"><p>
226        <code class="classname">array_allocator</code>
227        </p><p>
228          Allows allocations of known and fixed sizes using existing
229          global or external storage allocated via construction of
230          <code class="classname">std::tr1::array</code> objects. By using this
231          allocator, fixed size containers (including
232          <code class="classname">std::string</code>) can be used without
233          instances calling <code class="function">::operator new</code> and
234          <code class="function">::operator delete</code>. This capability
235          allows the use of STL abstractions without runtime
236          complications or overhead, even in situations such as program
237          startup. For usage examples, please consult the testsuite.
238        </p></li><li class="listitem"><p>
239        <code class="classname">debug_allocator</code>
240        </p><p>
241          A wrapper around an arbitrary allocator A.  It passes on
242          slightly increased size requests to A, and uses the extra
243          memory to store size information.  When a pointer is passed
244          to <code class="function">deallocate()</code>, the stored size is
245          checked, and <code class="function">assert()</code> is used to
246          guarantee they match.
247        </p></li><li class="listitem"><p>
248         <code class="classname">throw_allocator</code>
249         </p><p>
250           Includes memory tracking and marking abilities as well as hooks for
251           throwing exceptions at configurable intervals (including random,
252           all, none).
253         </p></li><li class="listitem"><p>
254        <code class="classname">__pool_alloc</code>
255        </p><p>
256          A high-performance, single pool allocator.  The reusable
257          memory is shared among identical instantiations of this type.
258          It calls through <code class="function">::operator new</code> to
259          obtain new memory when its lists run out.  If a client
260          container requests a block larger than a certain threshold
261          size, then the pool is bypassed, and the allocate/deallocate
262          request is passed to <code class="function">::operator new</code>
263          directly.
264        </p><p>
265          Older versions of this class take a boolean template
266          parameter, called <code class="varname">thr</code>, and an integer template
267          parameter, called <code class="varname">inst</code>.
268        </p><p>
269          The <code class="varname">inst</code> number is used to track additional memory
270       pools.  The point of the number is to allow multiple
271       instantiations of the classes without changing the semantics at
272       all.  All three of
273        </p><pre class="programlisting">
274     typedef  __pool_alloc&lt;true,0&gt;    normal;
275     typedef  __pool_alloc&lt;true,1&gt;    private;
276     typedef  __pool_alloc&lt;true,42&gt;   also_private;
277    </pre><p>
278      behave exactly the same way.  However, the memory pool for each type
279       (and remember that different instantiations result in different types)
280       remains separate.
281    </p><p>
282      The library uses <span class="emphasis"><em>0</em></span> in all its instantiations.  If you
283       wish to keep separate free lists for a particular purpose, use a
284       different number.
285    </p><p>The <code class="varname">thr</code> boolean determines whether the
286    pool should be manipulated atomically or not.  When
287    <code class="varname">thr</code> = <code class="constant">true</code>, the allocator
288    is thread-safe, while <code class="varname">thr</code> =
289    <code class="constant">false</code>, is slightly faster but unsafe for
290    multiple threads.
291    </p><p>
292      For thread-enabled configurations, the pool is locked with a
293      single big lock. In some situations, this implementation detail
294      may result in severe performance degradation.
295    </p><p>
296      (Note that the GCC thread abstraction layer allows us to provide
297      safe zero-overhead stubs for the threading routines, if threads
298      were disabled at configuration time.)
299    </p></li><li class="listitem"><p>
300        <code class="classname">__mt_alloc</code>
301        </p><p>
302          A high-performance fixed-size allocator with
303          exponentially-increasing allocations. It has its own
304          documentation, found <a class="link" href="ext_allocators.html#manual.ext.allocator.mt" title="mt_allocator">here</a>.
305        </p></li><li class="listitem"><p>
306        <code class="classname">bitmap_allocator</code>
307        </p><p>
308          A high-performance allocator that uses a bit-map to keep track
309          of the used and unused memory locations. It has its own
310          documentation, found <a class="link" href="bitmap_allocator.html" title="bitmap_allocator">here</a>.
311        </p></li></ol></div></div><div class="bibliography" title="Bibliography"><div class="titlepage"><div><div><h4 class="title"><a id="allocator.biblio"/>Bibliography</h4></div></div></div><div class="biblioentry"><a id="id555317"/><p><span class="citetitle"><em class="citetitle">
312     ISO/IEC 14882:1998 Programming languages - C++
313     </em>. </span>
314       isoc++_1998
315     <span class="pagenums">20.4 Memory. </span></p></div><div class="biblioentry"><a id="id555332"/><p><span class="biblioid">
316     . </span><span class="citetitle"><em class="citetitle">
317       The Standard Librarian: What Are Allocators Good For?
318     </em>. </span><span class="author"><span class="firstname">Matt</span> <span class="surname">Austern</span>. </span><span class="publisher"><span class="publishername">
319         C/C++ Users Journal
320       . </span></span></p></div><div class="biblioentry"><a id="id555365"/><p><span class="biblioid">
321     . </span><span class="citetitle"><em class="citetitle">
322       The Hoard Memory Allocator
323     </em>. </span><span class="author"><span class="firstname">Emery</span> <span class="surname">Berger</span>. </span></p></div><div class="biblioentry"><a id="id555391"/><p><span class="biblioid">
324     . </span><span class="citetitle"><em class="citetitle">
325       Reconsidering Custom Memory Allocation
326     </em>. </span><span class="author"><span class="firstname">Emery</span> <span class="surname">Berger</span>. </span><span class="author"><span class="firstname">Ben</span> <span class="surname">Zorn</span>. </span><span class="author"><span class="firstname">Kathryn</span> <span class="surname">McKinley</span>. </span><span class="copyright">Copyright © 2002 OOPSLA. </span></p></div><div class="biblioentry"><a id="id555444"/><p><span class="biblioid">
327     . </span><span class="citetitle"><em class="citetitle">
328       Allocator Types
329     </em>. </span><span class="author"><span class="firstname">Klaus</span> <span class="surname">Kreft</span>. </span><span class="author"><span class="firstname">Angelika</span> <span class="surname">Langer</span>. </span><span class="publisher"><span class="publishername">
330         C/C++ Users Journal
331       . </span></span></p></div><div class="biblioentry"><a id="id555486"/><p><span class="citetitle"><em class="citetitle">The C++ Programming Language</em>. </span><span class="author"><span class="firstname">Bjarne</span> <span class="surname">Stroustrup</span>. </span><span class="copyright">Copyright © 2000 . </span><span class="pagenums">19.4 Allocators. </span><span class="publisher"><span class="publishername">
332         Addison Wesley
333       . </span></span></p></div><div class="biblioentry"><a id="id555523"/><p><span class="citetitle"><em class="citetitle">Yalloc: A Recycling C++ Allocator</em>. </span><span class="author"><span class="firstname">Felix</span> <span class="surname">Yen</span>. </span></p></div></div></div><div class="section" title="auto_ptr"><div class="titlepage"><div><div><h3 class="title"><a id="std.util.memory.auto_ptr"/>auto_ptr</h3></div></div></div><div class="section" title="Limitations"><div class="titlepage"><div><div><h4 class="title"><a id="auto_ptr.limitations"/>Limitations</h4></div></div></div><p>Explaining all of the fun and delicious things that can
334    happen with misuse of the <code class="classname">auto_ptr</code> class
335    template (called <acronym class="acronym">AP</acronym> here) would take some
336    time. Suffice it to say that the use of <acronym class="acronym">AP</acronym>
337    safely in the presence of copying has some subtleties.
338    </p><p>
339      The AP class is a really
340       nifty idea for a smart pointer, but it is one of the dumbest of
341       all the smart pointers -- and that's fine.
342    </p><p>
343      AP is not meant to be a supersmart solution to all resource
344       leaks everywhere.  Neither is it meant to be an effective form
345       of garbage collection (although it can help, a little bit).
346       And it can <span class="emphasis"><em>not</em></span>be used for arrays!
347    </p><p>
348      <acronym class="acronym">AP</acronym> is meant to prevent nasty leaks in the
349      presence of exceptions.  That's <span class="emphasis"><em>all</em></span>.  This
350      code is AP-friendly:
351    </p><pre class="programlisting">
352     // Not a recommend naming scheme, but good for web-based FAQs.
353     typedef std::auto_ptr&lt;MyClass&gt;  APMC;
354
355     extern function_taking_MyClass_pointer (MyClass*);
356     extern some_throwable_function ();
357
358     void func (int data)
359     {
360         APMC  ap (new MyClass(data));
361
362         some_throwable_function();   // this will throw an exception
363
364         function_taking_MyClass_pointer (ap.get());
365     }
366    </pre><p>When an exception gets thrown, the instance of MyClass that's
367       been created on the heap will be <code class="function">delete</code>'d as the stack is
368       unwound past <code class="function">func()</code>.
369    </p><p>Changing that code as follows is not <acronym class="acronym">AP</acronym>-friendly:
370    </p><pre class="programlisting">
371         APMC  ap (new MyClass[22]);
372    </pre><p>You will get the same problems as you would without the use
373       of <acronym class="acronym">AP</acronym>:
374    </p><pre class="programlisting">
375         char*  array = new char[10];       // array new...
376         ...
377         delete array;                      // ...but single-object delete
378    </pre><p>
379      AP cannot tell whether the pointer you've passed at creation points
380       to one or many things.  If it points to many things, you are about
381       to die.  AP is trivial to write, however, so you could write your
382       own <code class="code">auto_array_ptr</code> for that situation (in fact, this has
383       been done many times; check the mailing lists, Usenet, Boost, etc).
384    </p></div><div class="section" title="Use in Containers"><div class="titlepage"><div><div><h4 class="title"><a id="auto_ptr.using"/>Use in Containers</h4></div></div></div><p>
385   </p><p>All of the <a class="link" href="containers.html" title="Chapter 9.  Containers">containers</a>
386       described in the standard library require their contained types
387       to have, among other things, a copy constructor like this:
388   </p><pre class="programlisting">
389     struct My_Type
390     {
391         My_Type (My_Type const&amp;);
392     };
393    </pre><p>
394      Note the const keyword; the object being copied shouldn't change.
395      The template class <code class="code">auto_ptr</code> (called AP here) does not
396      meet this requirement.  Creating a new AP by copying an existing
397      one transfers ownership of the pointed-to object, which means that
398      the AP being copied must change, which in turn means that the
399      copy ctors of AP do not take const objects.
400    </p><p>
401      The resulting rule is simple: <span class="emphasis"><em>Never ever use a
402      container of auto_ptr objects</em></span>. The standard says that
403      <span class="quote">“<span class="quote">undefined</span>”</span> behavior is the result, but it is
404      guaranteed to be messy.
405    </p><p>
406      To prevent you from doing this to yourself, the
407       <a class="link" href="ext_compile_checks.html" title="Chapter 16. Compile Time Checks">concept checks</a> built
408       in to this implementation will issue an error if you try to
409       compile code like this:
410    </p><pre class="programlisting">
411     #include &lt;vector&gt;
412     #include &lt;memory&gt;
413
414     void f()
415     {
416         std::vector&lt; std::auto_ptr&lt;int&gt; &gt;   vec_ap_int;
417     }
418    </pre><p>
419 Should you try this with the checks enabled, you will see an error.
420    </p></div></div><div class="section" title="shared_ptr"><div class="titlepage"><div><div><h3 class="title"><a id="std.util.memory.shared_ptr"/>shared_ptr</h3></div></div></div><p>
421 The shared_ptr class template stores a pointer, usually obtained via new,
422 and implements shared ownership semantics.
423 </p><div class="section" title="Requirements"><div class="titlepage"><div><div><h4 class="title"><a id="shared_ptr.req"/>Requirements</h4></div></div></div><p>
424   </p><p>
425     The standard deliberately doesn't require a reference-counted
426     implementation, allowing other techniques such as a
427     circular-linked-list.
428   </p><p>
429     At the time of writing the C++0x working paper doesn't mention how
430     threads affect shared_ptr, but it is likely to follow the existing
431     practice set by <code class="classname">boost::shared_ptr</code>.  The
432     shared_ptr in libstdc++ is derived from Boost's, so the same rules
433     apply.
434   </p><p>
435   </p></div><div class="section" title="Design Issues"><div class="titlepage"><div><div><h4 class="title"><a id="shared_ptr.design_issues"/>Design Issues</h4></div></div></div><p>
436 The <code class="classname">shared_ptr</code> code is kindly donated to GCC by the Boost
437 project and the original authors of the code. The basic design and
438 algorithms are from Boost, the notes below describe details specific to
439 the GCC implementation. Names have been uglified in this implementation,
440 but the design should be recognisable to anyone familiar with the Boost
441 1.32 shared_ptr.
442   </p><p>
443 The basic design is an abstract base class, <code class="code">_Sp_counted_base</code> that
444 does the reference-counting and calls virtual functions when the count
445 drops to zero.
446 Derived classes override those functions to destroy resources in a context
447 where the correct dynamic type is known. This is an application of the
448 technique known as type erasure.
449   </p></div><div class="section" title="Implementation"><div class="titlepage"><div><div><h4 class="title"><a id="shared_ptr.impl"/>Implementation</h4></div></div></div><div class="section" title="Class Hierarchy"><div class="titlepage"><div><div><h5 class="title"><a id="id555883"/>Class Hierarchy</h5></div></div></div><p>
450 A <code class="classname">shared_ptr&lt;T&gt;</code> contains a pointer of
451 type <span class="type">T*</span> and an object of type
452 <code class="classname">__shared_count</code>. The shared_count contains a
453 pointer of type <span class="type">_Sp_counted_base*</span> which points to the
454 object that maintains the reference-counts and destroys the managed
455 resource.
456     </p><div class="variablelist"><dl><dt><span class="term"><code class="classname">_Sp_counted_base&lt;Lp&gt;</code></span></dt><dd><p>
457 The base of the hierarchy is parameterized on the lock policy (see below.)
458 _Sp_counted_base doesn't depend on the type of pointer being managed,
459 it only maintains the reference counts and calls virtual functions when
460 the counts drop to zero. The managed object is destroyed when the last
461 strong reference is dropped, but the _Sp_counted_base itself must exist
462 until the last weak reference is dropped.
463     </p></dd><dt><span class="term"><code class="classname">_Sp_counted_base_impl&lt;Ptr, Deleter, Lp&gt;</code></span></dt><dd><p>
464 Inherits from _Sp_counted_base and stores a pointer of type <span class="type">Ptr</span>
465 and a deleter of type <code class="code">Deleter</code>.  <code class="code">_Sp_deleter</code> is
466 used when the user doesn't supply a custom deleter. Unlike Boost's, this
467 default deleter is not "checked" because GCC already issues a warning if
468 <code class="function">delete</code> is used with an incomplete type.
469 This is the only derived type used by <code class="classname">shared_ptr&lt;Ptr&gt;</code>
470 and it is never used by <code class="classname">shared_ptr</code>, which uses one of
471 the following types, depending on how the shared_ptr is constructed.
472     </p></dd><dt><span class="term"><code class="classname">_Sp_counted_ptr&lt;Ptr, Lp&gt;</code></span></dt><dd><p>
473 Inherits from _Sp_counted_base and stores a pointer of type <span class="type">Ptr</span>,
474 which is passed to <code class="function">delete</code> when the last reference is dropped.
475 This is the simplest form and is used when there is no custom deleter or
476 allocator.
477     </p></dd><dt><span class="term"><code class="classname">_Sp_counted_deleter&lt;Ptr, Deleter, Alloc&gt;</code></span></dt><dd><p>
478 Inherits from _Sp_counted_ptr and adds support for custom deleter and
479 allocator. Empty Base Optimization is used for the allocator. This class
480 is used even when the user only provides a custom deleter, in which case
481 <code class="classname">allocator</code> is used as the allocator.
482     </p></dd><dt><span class="term"><code class="classname">_Sp_counted_ptr_inplace&lt;Tp, Alloc, Lp&gt;</code></span></dt><dd><p>
483 Used by <code class="code">allocate_shared</code> and <code class="code">make_shared</code>.
484 Contains aligned storage to hold an object of type <span class="type">Tp</span>,
485 which is constructed in-place with placement <code class="function">new</code>.
486 Has a variadic template constructor allowing any number of arguments to
487 be forwarded to <span class="type">Tp</span>'s constructor.
488 Unlike the other <code class="classname">_Sp_counted_*</code> classes, this one is parameterized on the
489 type of object, not the type of pointer; this is purely a convenience
490 that simplifies the implementation slightly.
491     </p></dd></dl></div></div><div class="section" title="Thread Safety"><div class="titlepage"><div><div><h5 class="title"><a id="id556062"/>Thread Safety</h5></div></div></div><p>
492 C++0x-only features are: rvalue-ref/move support, allocator support,
493 aliasing constructor, make_shared &amp; allocate_shared. Additionally,
494 the constructors taking <code class="classname">auto_ptr</code> parameters are
495 deprecated in C++0x mode.
496     </p><p>
497 The
498 <a class="link" href="http://boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety">Thread
499 Safety</a> section of the Boost shared_ptr documentation says "shared_ptr
500 objects offer the same level of thread safety as built-in types."
501 The implementation must ensure that concurrent updates to separate shared_ptr
502 instances are correct even when those instances share a reference count e.g.
503 </p><pre class="programlisting">
504 shared_ptr&lt;A&gt; a(new A);
505 shared_ptr&lt;A&gt; b(a);
506
507 // Thread 1     // Thread 2
508    a.reset();      b.reset();
509 </pre><p>
510 The dynamically-allocated object must be destroyed by exactly one of the
511 threads. Weak references make things even more interesting.
512 The shared state used to implement shared_ptr must be transparent to the
513 user and invariants must be preserved at all times.
514 The key pieces of shared state are the strong and weak reference counts.
515 Updates to these need to be atomic and visible to all threads to ensure
516 correct cleanup of the managed resource (which is, after all, shared_ptr's
517 job!)
518 On multi-processor systems memory synchronisation may be needed so that
519 reference-count updates and the destruction of the managed resource are
520 race-free.
521 </p><p>
522 The function <code class="function">_Sp_counted_base::_M_add_ref_lock()</code>, called when
523 obtaining a shared_ptr from a weak_ptr, has to test if the managed
524 resource still exists and either increment the reference count or throw
525 <code class="classname">bad_weak_ptr</code>.
526 In a multi-threaded program there is a potential race condition if the last
527 reference is dropped (and the managed resource destroyed) between testing
528 the reference count and incrementing it, which could result in a shared_ptr
529 pointing to invalid memory.
530 </p><p>
531 The Boost shared_ptr (as used in GCC) features a clever lock-free
532 algorithm to avoid the race condition, but this relies on the
533 processor supporting an atomic <span class="emphasis"><em>Compare-And-Swap</em></span>
534 instruction. For other platforms there are fall-backs using mutex
535 locks.  Boost (as of version 1.35) includes several different
536 implementations and the preprocessor selects one based on the
537 compiler, standard library, platform etc. For the version of
538 shared_ptr in libstdc++ the compiler and library are fixed, which
539 makes things much simpler: we have an atomic CAS or we don't, see Lock
540 Policy below for details.
541 </p></div><div class="section" title="Selecting Lock Policy"><div class="titlepage"><div><div><h5 class="title"><a id="id556132"/>Selecting Lock Policy</h5></div></div></div><p>
542     </p><p>
543 There is a single <code class="classname">_Sp_counted_base</code> class,
544 which is a template parameterized on the enum
545 <span class="type">__gnu_cxx::_Lock_policy</span>.  The entire family of classes is
546 parameterized on the lock policy, right up to
547 <code class="classname">__shared_ptr</code>, <code class="classname">__weak_ptr</code> and
548 <code class="classname">__enable_shared_from_this</code>. The actual
549 <code class="classname">std::shared_ptr</code> class inherits from
550 <code class="classname">__shared_ptr</code> with the lock policy parameter
551 selected automatically based on the thread model and platform that
552 libstdc++ is configured for, so that the best available template
553 specialization will be used. This design is necessary because it would
554 not be conforming for <code class="classname">shared_ptr</code> to have an
555 extra template parameter, even if it had a default value.  The
556 available policies are:
557     </p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
558        <span class="type">_S_Atomic</span>
559        </p><p>
560 Selected when GCC supports a builtin atomic compare-and-swap operation
561 on the target processor (see <a class="link" href="http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html">Atomic
562 Builtins</a>.)  The reference counts are maintained using a lock-free
563 algorithm and GCC's atomic builtins, which provide the required memory
564 synchronisation.
565        </p></li><li class="listitem"><p>
566        <span class="type">_S_Mutex</span>
567        </p><p>
568 The _Sp_counted_base specialization for this policy contains a mutex,
569 which is locked in add_ref_lock(). This policy is used when GCC's atomic
570 builtins aren't available so explicit memory barriers are needed in places.
571        </p></li><li class="listitem"><p>
572        <span class="type">_S_Single</span>
573        </p><p>
574 This policy uses a non-reentrant add_ref_lock() with no locking. It is
575 used when libstdc++ is built without <code class="literal">--enable-threads</code>.
576        </p></li></ol></div><p>
577        For all three policies, reference count increments and
578        decrements are done via the functions in
579        <code class="filename">ext/atomicity.h</code>, which detect if the program
580        is multi-threaded.  If only one thread of execution exists in
581        the program then less expensive non-atomic operations are used.
582      </p></div><div class="section" title="Dual C++0x and TR1 Implementation"><div class="titlepage"><div><div><h5 class="title"><a id="id556254"/>Dual C++0x and TR1 Implementation</h5></div></div></div><p>
583 The interface of <code class="classname">tr1::shared_ptr</code> was extended for C++0x
584 with support for rvalue-references and the other features from N2351.
585 The <code class="classname">_Sp_counted_base</code> base class is implemented in
586 <code class="filename">tr1/boost_sp_shared_count.h</code> and is common to the TR1
587 and C++0x versions of <code class="classname">shared_ptr</code>.
588 </p><p>
589 The classes derived from <code class="classname">_Sp_counted_base</code> (see Class Hierarchy
590 above) and <code class="classname">__shared_count</code> are implemented separately for C++0x
591 and TR1, in <code class="filename">bits/shared_ptr.h</code> and
592 <code class="filename">tr1/shared_ptr.h</code> respectively.
593 </p><p>
594 The TR1 implementation is considered relatively stable, so is unlikely to
595 change unless bug fixes require it.  If the code that is common to both
596 C++0x and TR1 modes needs to diverge further then it might be necessary to
597 duplicate <code class="classname">_Sp_counted_base</code> and only make changes to
598 the C++0x version.
599 </p></div><div class="section" title="Related functions and classes"><div class="titlepage"><div><div><h5 class="title"><a id="id556310"/>Related functions and classes</h5></div></div></div><div class="variablelist"><dl><dt><span class="term"><code class="code">dynamic_pointer_cast</code>, <code class="code">static_pointer_cast</code>,
600 <code class="code">const_pointer_cast</code></span></dt><dd><p>
601 As noted in N2351, these functions can be implemented non-intrusively using
602 the alias constructor.  However the aliasing constructor is only available
603 in C++0x mode, so in TR1 mode these casts rely on three non-standard
604 constructors in shared_ptr and __shared_ptr.
605 In C++0x mode these constructors and the related tag types are not needed.
606     </p></dd><dt><span class="term"><code class="code">enable_shared_from_this</code></span></dt><dd><p>
607 The clever overload to detect a base class of type
608 <code class="code">enable_shared_from_this</code> comes straight from Boost.
609 There is an extra overload for <code class="code">__enable_shared_from_this</code> to
610 work smoothly with <code class="code">__shared_ptr&lt;Tp, Lp&gt;</code> using any lock
611 policy.
612     </p></dd><dt><span class="term"><code class="code">make_shared</code>, <code class="code">allocate_shared</code></span></dt><dd><p>
613 <code class="code">make_shared</code> simply forwards to <code class="code">allocate_shared</code>
614 with <code class="code">std::allocator</code> as the allocator.
615 Although these functions can be implemented non-intrusively using the
616 alias constructor, if they have access to the implementation then it is
617 possible to save storage and reduce the number of heap allocations. The
618 newly constructed object and the _Sp_counted_* can be allocated in a single
619 block and the standard says implementations are "encouraged, but not required,"
620 to do so. This implementation provides additional non-standard constructors
621 (selected with the type <code class="code">_Sp_make_shared_tag</code>) which create an
622 object of type <code class="code">_Sp_counted_ptr_inplace</code> to hold the new object.
623 The returned <code class="code">shared_ptr&lt;A&gt;</code> needs to know the address of the
624 new <code class="code">A</code> object embedded in the <code class="code">_Sp_counted_ptr_inplace</code>,
625 but it has no way to access it.
626 This implementation uses a "covert channel" to return the address of the
627 embedded object when <code class="code">get_deleter&lt;_Sp_make_shared_tag&gt;()</code>
628 is called.  Users should not try to use this.
629 As well as the extra constructors, this implementation also needs some
630 members of _Sp_counted_deleter to be protected where they could otherwise
631 be private.
632     </p></dd></dl></div></div></div><div class="section" title="Use"><div class="titlepage"><div><div><h4 class="title"><a id="shared_ptr.using"/>Use</h4></div></div></div><div class="section" title="Examples"><div class="titlepage"><div><div><h5 class="title"><a id="id556459"/>Examples</h5></div></div></div><p>
633       Examples of use can be found in the testsuite, under
634       <code class="filename">testsuite/tr1/2_general_utilities/shared_ptr</code>,
635       <code class="filename">testsuite/20_util/shared_ptr</code>
636       and
637       <code class="filename">testsuite/20_util/weak_ptr</code>.
638     </p></div><div class="section" title="Unresolved Issues"><div class="titlepage"><div><div><h5 class="title"><a id="id556488"/>Unresolved Issues</h5></div></div></div><p>
639       The <span class="emphasis"><em><code class="classname">shared_ptr</code> atomic access</em></span>
640       clause in the C++0x working draft is not implemented in GCC.
641     </p><p>
642       The <span class="type">_S_single</span> policy uses atomics when used in MT
643       code, because it uses the same dispatcher functions that check
644       <code class="function">__gthread_active_p()</code>. This could be
645       addressed by providing template specialisations for some members
646       of <code class="classname">_Sp_counted_base&lt;_S_single&gt;</code>.
647     </p><p>
648       Unlike Boost, this implementation does not use separate classes
649       for the pointer+deleter and pointer+deleter+allocator cases in
650       C++0x mode, combining both into _Sp_counted_deleter and using
651       <code class="classname">allocator</code> when the user doesn't specify
652       an allocator.  If it was found to be beneficial an additional
653       class could easily be added.  With the current implementation,
654       the _Sp_counted_deleter and __shared_count constructors taking a
655       custom deleter but no allocator are technically redundant and
656       could be removed, changing callers to always specify an
657       allocator. If a separate pointer+deleter class was added the
658       __shared_count constructor would be needed, so it has been kept
659       for now.
660     </p><p>
661       The hack used to get the address of the managed object from
662       <code class="function">_Sp_counted_ptr_inplace::_M_get_deleter()</code>
663       is accessible to users. This could be prevented if
664       <code class="function">get_deleter&lt;_Sp_make_shared_tag&gt;()</code>
665       always returned NULL, since the hack only needs to work at a
666       lower level, not in the public API. This wouldn't be difficult,
667       but hasn't been done since there is no danger of accidental
668       misuse: users already know they are relying on unsupported
669       features if they refer to implementation details such as
670       _Sp_make_shared_tag.
671     </p><p>
672       tr1::_Sp_deleter could be a private member of tr1::__shared_count but it
673       would alter the ABI.
674     </p></div></div><div class="section" title="Acknowledgments"><div class="titlepage"><div><div><h4 class="title"><a id="shared_ptr.ack"/>Acknowledgments</h4></div></div></div><p>
675     The original authors of the Boost shared_ptr, which is really nice
676     code to work with, Peter Dimov in particular for his help and
677     invaluable advice on thread safety.  Phillip Jordan and Paolo
678     Carlini for the lock policy implementation.
679   </p></div><div class="bibliography" title="Bibliography"><div class="titlepage"><div><div><h4 class="title"><a id="shared_ptr.biblio"/>Bibliography</h4></div></div></div><div class="biblioentry"><a id="id556582"/><p><span class="biblioid">
680     . </span><span class="citetitle"><em class="citetitle">
681       Improving shared_ptr for C++0x, Revision 2
682     </em>. </span><span class="subtitle">
683       N2351
684     . </span></p></div><div class="biblioentry"><a id="id556604"/><p><span class="biblioid">
685     . </span><span class="citetitle"><em class="citetitle">
686       C++ Standard Library Active Issues List
687     </em>. </span><span class="subtitle">
688       N2456
689     . </span></p></div><div class="biblioentry"><a id="id556625"/><p><span class="biblioid">
690     . </span><span class="citetitle"><em class="citetitle">
691       Working Draft, Standard for Programming Language C++
692     </em>. </span><span class="subtitle">
693       N2461
694     . </span></p></div><div class="biblioentry"><a id="id556646"/><p><span class="biblioid">shared_ptr
695     . </span><span class="citetitle"><em class="citetitle">
696       Boost C++ Libraries documentation, shared_ptr
697     </em>. </span><span class="subtitle">
698       N2461
699     . </span></p></div></div></div></div><div class="navfooter"><hr/><table width="100%" summary="Navigation footer"><tr><td align="left"><a accesskey="p" href="pairs.html">Prev</a> </td><td align="center"><a accesskey="u" href="utilities.html">Up</a></td><td align="right"> <a accesskey="n" href="traits.html">Next</a></td></tr><tr><td align="left" valign="top">Pairs </td><td align="center"><a accesskey="h" href="../spine.html">Home</a></td><td align="right" valign="top"> Traits</td></tr></table></div></body></html>