OSDN Git Service

2007-01-18 Jerry DeLisle <jvdelisle@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / docs / html / 18_support / howto.html
1 <?xml version="1.0" encoding="ISO-8859-1"?>
2 <!DOCTYPE html
3           PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
4           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5
6 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
7 <head>
8    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
9    <meta name="AUTHOR" content="pme@gcc.gnu.org (Phil Edwards)" />
10    <meta name="KEYWORDS" content="HOWTO, libstdc++, GCC, g++, libg++, STL" />
11    <meta name="DESCRIPTION" content="HOWTO for the libstdc++ chapter 18." />
12    <meta name="GENERATOR" content="vi and eight fingers" />
13    <title>libstdc++ HOWTO:  Chapter 18: Library Support</title>
14 <link rel="StyleSheet" href="../lib3styles.css" type="text/css" />
15 <link rel="Start" href="../documentation.html" type="text/html"
16   title="GNU C++ Standard Library" />
17 <link rel="Prev" href="../17_intro/howto.html" type="text/html"
18   title="Library Introduction" />
19 <link rel="Next" href="../19_diagnostics/howto.html" type="text/html"
20   title="Diagnostics" />
21 <link rel="Copyright" href="../17_intro/license.html" type="text/html" />
22 <link rel="Help" href="../faq/index.html" type="text/html" title="F.A.Q." />
23 </head>
24 <body>
25
26 <h1 class="centered"><a name="top">Chapter 18:  Library Support</a></h1>
27
28 <p>Chapter 18 deals with the functions called and objects created
29    automatically during the course of a program's existence.
30 </p>
31 <p>While we can't reproduce the contents of the Standard here (you need to
32    get your own copy from your nation's member body; see our homepage for
33    help), we can mention a couple of changes in what kind of support a C++
34    program gets from the Standard Library.
35 </p>
36
37
38 <!-- ####################################################### -->
39 <hr />
40 <h1>Contents</h1>
41 <ul>
42    <li><a href="#1">Types</a></li>
43    <li><a href="#2">Implementation properties</a></li>
44    <li><a href="#3">Start and Termination</a></li>
45    <li><a href="#4">Verbose <code>terminate</code></a></li>
46    <li><a href="#5">Dynamic memory management</a></li>
47    <li><a href="#6">RTTI, the ABI, and demangling</a></li>
48 </ul>
49
50 <hr />
51
52 <!-- ####################################################### -->
53
54 <h2><a name="1">Types</a></h2>
55    <p>All the types that you're used to in C are here in one form or
56       another.  The only change that might affect people is the type of
57       NULL:  while it is required to be a macro, the definition of that
58       macro is <em>not</em> allowed to be <code>(void*)0</code>, which is
59       often used in C.
60    </p>
61    <p>In g++, NULL is #define'd to be <code>__null</code>, a magic keyword
62       extension of g++.
63    </p>
64    <p>The biggest problem of #defining NULL to be something like
65       &quot;0L&quot; is that the compiler will view that as a long integer
66       before it views it as a pointer, so overloading won't do what you
67       expect.  (This is why g++ has a magic extension, so that NULL is
68       always a pointer.)
69    </p>
70    <p>In his book
71       <a href="http://www.awprofessional.com/titles/0-201-92488-9/"><em>Effective C++</em></a>,
72       Scott Meyers points out that the best way to solve this problem is to
73       not overload on pointer-vs-integer types to begin with.  He also
74       offers a way to make your own magic NULL that will match pointers
75       before it matches integers:
76    </p>
77    <pre>
78    const                             // this is a const object...
79    class {
80    public:
81      template&lt;class T&gt;               // convertible to any type
82        operator T*() const           // of null non-member
83        { return 0; }                 // pointer...
84
85      template&lt;class C, class T&gt;      // or any type of null
86        operator T C::*() const       // member pointer...
87        { return 0; }
88
89    private:
90      void operator&amp;() const;         // whose address can't be
91                                      // taken (see Item 27)...
92
93    } NULL;                           // and whose name is NULL
94    </pre>
95    <p>(Cribbed from the published version of
96       <a href="http://www.awprofessional.com/titles/0-201-31015-5/">the
97       Effective C++ CD</a>, reproduced here with permission.)
98    </p>
99    <p>If you aren't using g++ (why?), but you do have a compiler which
100       supports member function templates, then you can use this definition
101       of NULL (be sure to #undef any existing versions).  It only helps if
102       you actually use NULL in function calls, though; if you make a call of
103       <code>foo(0);</code> instead of <code>foo(NULL);</code>, then you're back
104       where you started.
105    </p>
106    <p><strong>Added Note:</strong>  When we contacted Dr. Meyers to ask
107       permission to
108       print this stuff, it prompted him to run this code through current
109       compilers to see what the state of the art is with respect to member
110       template functions.  He posted
111       <a href="http://groups.google.com/groups?oi=djq&amp;selm=an_644660779">
112       an article to Usenet</a> after discovering that the code above is not
113       valid!  Even though it has no data members, it still needs a
114       user-defined constructor (which means that the class needs a type name
115       after all).  The ctor can have an empty body; it just needs to be
116       there.  (Stupid requirement?  We think so too, and this will probably
117       be changed in the language itself.)
118    </p>
119    <p>Return <a href="#top">to top of page</a> or
120       <a href="../faq/index.html">to the FAQ</a>.
121    </p>
122
123 <hr />
124 <h2><a name="2">Implementation properties</a></h2>
125    <h3><code>&lt;limits&gt;</code></h3>
126    <p>This header mainly defines traits classes to give access to various
127    implementation defined-aspects of the fundamental types.  The
128    traits classes -- fourteen in total -- are all specializations of the 
129    template class <code>numeric_limits</code>, documented
130    <a href="http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/structstd_1_1numeric__limits.html">here</a>
131    and defined as follows:
132    </p>
133    <pre>
134    template&lt;typename T&gt; struct class {
135       static const bool is_specialized;
136       static T max() throw();
137       static T min() throw();
138
139       static const int digits;
140       static const int digits10;
141       static const bool is_signed;
142       static const bool is_integer;
143       static const bool is_exact;
144       static const int radix;
145       static T epsilon() throw();
146       static T round_error() throw();
147
148       static const int min_exponent;
149       static const int min_exponent10;
150       static const int max_exponent;
151       static const int max_exponent10;
152
153       static const bool has_infinity;
154       static const bool has_quiet_NaN;
155       static const bool has_signaling_NaN;
156       static const float_denorm_style has_denorm;
157       static const bool has_denorm_loss;
158       static T infinity() throw();
159       static T quiet_NaN() throw();
160       static T denorm_min() throw();
161
162       static const bool is_iec559;
163       static const bool is_bounded;
164       static const bool is_modulo;
165
166       static const bool traps;
167       static const bool tinyness_before;
168       static const float_round_style round_style;
169    };</pre>
170    <p>Return <a href="#top">to top of page</a> or
171       <a href="../faq/index.html">to the FAQ</a>.
172    </p>
173
174 <hr />
175 <h2><a name="3">Start and Termination</a></h2>
176    <p>Not many changes here to <code>&lt;cstdlib&gt;</code> (the old stdlib.h).
177       You should note that the <code>abort()</code> function does not call
178       the destructors of automatic nor static objects, so if you're depending
179       on those to do cleanup, it isn't going to happen.  (The functions
180       registered with <code>atexit()</code> don't get called either, so you
181       can forget about that possibility, too.)
182    </p>
183    <p>The good old <code>exit()</code> function can be a bit funky, too, until
184       you look closer.  Basically, three points to remember are:
185    </p>
186       <ol>
187         <li>Static objects are destroyed in reverse order of their creation.
188         </li>
189         <li>Functions registered with <code>atexit()</code> are called in
190             reverse order of registration, once per registration call.
191             (This isn't actually new.)
192         </li>
193         <li>The previous two actions are &quot;interleaved,&quot; that is,
194             given this pseudocode:
195             <pre>
196               extern "C or C++" void  f1 (void);
197               extern "C or C++" void  f2 (void);
198
199               static Thing obj1;
200               atexit(f1);
201               static Thing obj2;
202               atexit(f2);
203             </pre>
204             then at a call of <code>exit()</code>, f2 will be called, then
205             obj2 will be destroyed, then f1 will be called, and finally obj1
206             will be destroyed.  If f1 or f2 allow an exception to propagate
207             out of them, Bad Things happen.
208         </li>
209       </ol>
210    <p>Note also that <code>atexit()</code> is only required to store 32
211       functions, and the compiler/library might already be using some of
212       those slots.  If you think you may run out, we recommend using
213       the xatexit/xexit combination from libiberty, which has no such limit.
214    </p>
215    <p>Return <a href="#top">to top of page</a> or
216       <a href="../faq/index.html">to the FAQ</a>.
217    </p>
218
219 <hr />
220 <h2><a name="4">Verbose <code>terminate</code></a></h2>
221    <p>If you are having difficulty with uncaught exceptions and want a
222       little bit of help debugging the causes of the core dumps, you can
223       make use of a GNU extension in GCC 3.1 and later:
224    </p>
225    <pre>
226    #include &lt;exception&gt;
227
228    int main()
229    {
230        std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
231        ...
232
233        throw <em>anything</em>;
234    }</pre>
235    <p>The <code> __verbose_terminate_handler </code> function obtains the name
236       of the current exception, attempts to demangle it, and prints it to
237       stderr.  If the exception is derived from <code> std::exception </code>
238       then the output from <code>what()</code> will be included.
239    </p>
240    <p>Any replacement termination function is required to kill the program
241       without returning; this one calls abort.
242    </p>
243    <p>For example:
244    </p>
245    <pre>
246    #include &lt;exception&gt;
247    #include &lt;stdexcept&gt;
248
249    struct argument_error : public std::runtime_error
250    {  
251      argument_error(const std::string&amp; s): std::runtime_error(s) { }
252    };
253
254    int main(int argc)
255    {
256      std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
257      if (argc &gt; 5)
258        throw argument_error(&quot;argc is greater than 5!&quot;);
259      else
260        throw argc;
261    }
262    </pre>
263    <p>In GCC 3.1 and later, this gives
264    </p>
265    <pre>
266    % ./a.out
267    terminate called after throwing a `int'
268    Aborted
269    % ./a.out f f f f f f f f f f f
270    terminate called after throwing an instance of `argument_error'
271    what(): argc is greater than 5!
272    Aborted
273    %</pre>
274    <p>The 'Aborted' line comes from the call to abort(), of course.
275    </p>
276    <p><strong>UPDATE:</strong> Starting with GCC 3.4, this is the default
277       termination handler; nothing need be done to use it.  To go back to
278       the previous &quot;silent death&quot; method, simply include
279       <code>&lt;exception&gt;</code> and <code>&lt;cstdlib&gt;</code>,
280       and call
281    </p>
282    <pre>
283        std::set_terminate(std::abort);</pre>
284
285 <p>
286    This function will attempt to write to stderr.  If your application
287     closes stderr or redirects it to an inappropriate location,
288     <code>__verbose_terminate_handler</code> will behave in an
289     unspecified manner.
290 </p>
291
292    <p>Return <a href="#top">to top of page</a> or
293       <a href="../faq/index.html">to the FAQ</a>.
294    </p>
295
296
297 <hr />
298 <h2><a name="5">Dynamic memory management</a></h2>
299    <p>There are six flavors each of <code>new</code> and
300       <code>delete</code>, so make certain that you're using the right
301       ones!  Here are quickie descriptions of <code>new</code>:
302         </p>
303    <ul>
304       <li>single object form, throwing a <code>bad_alloc</code> on errors;
305           this is what most people are used to using</li>
306       <li>single object &quot;nothrow&quot; form, returning NULL on errors</li>
307       <li>array new, throwing <code>bad_alloc</code> on errors</li>
308       <li>array nothrow new, returning NULL on errors</li>
309       <li>placement new, which does nothing (like it's supposed to)</li>
310       <li>placement array new, which also does nothing</li>
311    </ul>
312    <p>They are distinguished by the parameters that you pass to them, like
313       any other overloaded function.  The six flavors of <code>delete</code>
314       are distinguished the same way, but none of them are allowed to throw
315       an exception under any circumstances anyhow.  (They match up for
316       completeness' sake.)
317    </p>
318    <p>Remember that it is perfectly okay to call <code>delete</code> on a
319       NULL pointer!  Nothing happens, by definition.  That is not the
320       same thing as deleting a pointer twice.
321    </p>
322    <p>By default, if one of the &quot;throwing <code>new</code>s&quot; can't
323       allocate the memory requested, it tosses an instance of a
324       <code>bad_alloc</code> exception (or, technically, some class derived
325       from it).  You can change this by writing your own function (called a
326       new-handler) and then registering it with <code>set_new_handler()</code>:
327         </p>
328    <pre>
329    typedef void (*PFV)(void);
330
331    static char*  safety;
332    static PFV    old_handler;
333
334    void my_new_handler ()
335    {
336        delete[] safety;
337        popup_window ("Dude, you are running low on heap memory.  You
338                       should, like, close some windows, or something.
339                       The next time you run out, we're gonna burn!");
340        set_new_handler (old_handler);
341        return;
342    }
343
344    int main ()
345    {
346        safety = new char[500000];
347        old_handler = set_new_handler (&amp;my_new_handler);
348        ...
349    }
350    </pre>
351    <p><code>bad_alloc</code> is derived from the base <code>exception</code>
352       class defined in Chapter 19.
353    </p>
354    <p>Return <a href="#top">to top of page</a> or
355       <a href="../faq/index.html">to the FAQ</a>.
356    </p>
357
358 <hr />
359 <h2><a name="6">RTTI, the ABI, and demangling</a></h2>
360    <p>If you have read the <a href="../documentation.html#4">source
361       documentation</a> for <code> namespace abi </code> then you are aware
362       of the cross-vendor C++ ABI which we use.  One of the exposed
363       functions is the one which we use for demangling in programs like
364       <code>c++filt</code>, and you can use it yourself as well.
365    </p>
366    <p>(The function itself might use different demanglers, but that's the
367       whole point of abstract interfaces.  If we change the implementation,
368       you won't notice.)
369    </p>
370    <p>Probably the only times you'll be interested in demangling at runtime
371       are when you're seeing <code>typeid</code> strings in RTTI, or when
372       you're handling the runtime-support exception classes.  For example:
373    </p>
374    <pre>
375 #include &lt;exception&gt;
376 #include &lt;iostream&gt;
377 #include &lt;cxxabi.h&gt;
378
379 struct empty { };
380
381 template &lt;typename T, int N&gt;
382   struct bar { };
383
384
385 int main()
386 {
387   int     status;
388   char   *realname;
389
390   // exception classes not in &lt;stdexcept&gt;, thrown by the implementation
391   // instead of the user
392   std::bad_exception  e;
393   realname = abi::__cxa_demangle(e.what(), 0, 0, &amp;status);
394   std::cout &lt;&lt; e.what() &lt;&lt; "\t=&gt; " &lt;&lt; realname &lt;&lt; "\t: " &lt;&lt; status &lt;&lt; '\n';
395   free(realname);
396
397
398   // typeid
399   bar&lt;empty,17&gt;          u;
400   const std::type_info  &amp;ti = typeid(u);
401
402   realname = abi::__cxa_demangle(ti.name(), 0, 0, &amp;status);
403   std::cout &lt;&lt; ti.name() &lt;&lt; "\t=&gt; " &lt;&lt; realname &lt;&lt; "\t: " &lt;&lt; status &lt;&lt; '\n';
404   free(realname);
405
406   return 0;
407 }</pre>
408    <p>With GCC 3.1 and later, this prints
409    </p>
410    <pre>
411       St13bad_exception       =&gt; std::bad_exception   : 0
412       3barI5emptyLi17EE       =&gt; bar&lt;empty, 17&gt;       : 0 </pre>
413    <p>The demangler interface is described in the source documentation
414       linked to above.  It is actually written in C, so you don't need to
415       be writing C++ in order to demangle C++.  (That also means we have to
416       use crummy memory management facilities, so don't forget to free()
417       the returned char array.)
418    </p>
419    <p>Return <a href="#top">to top of page</a> or
420       <a href="../faq/index.html">to the FAQ</a>.
421    </p>
422
423
424 <!-- ####################################################### -->
425
426 <hr />
427 <p class="fineprint"><em>
428 See <a href="../17_intro/license.html">license.html</a> for copying conditions.
429 Comments and suggestions are welcome, and may be sent to
430 <a href="mailto:libstdc++@gcc.gnu.org">the libstdc++ mailing list</a>.
431 </em></p>
432
433
434 </body>
435 </html>