Home | History | Annotate | Line # | Download | only in manual
      1 <chapter xmlns="http://docbook.org/ns/docbook" version="5.0"
      2 	 xml:id="std.support" xreflabel="Support">
      3 <?dbhtml filename="support.html"?>
      4 
      5 <info><title>
      6   Support
      7   <indexterm><primary>Support</primary></indexterm>
      8 </title>
      9   <keywordset>
     10     <keyword>ISO C++</keyword>
     11     <keyword>library</keyword>
     12   </keywordset>
     13 </info>
     14 
     15   <para>
     16     This part deals with the functions called and objects created
     17     automatically during the course of a program's existence.
     18   </para>
     19 
     20   <para>
     21     While we can't reproduce the contents of the Standard here (you
     22     need to get your own copy from your nation's member body; see our
     23     homepage for help), we can mention a couple of changes in what
     24     kind of support a C++ program gets from the Standard Library.
     25   </para>
     26 
     27 <section xml:id="std.support.types" xreflabel="Types"><info><title>Types</title></info>
     28   <?dbhtml filename="fundamental_types.html"?>
     29 
     30   <section xml:id="std.support.types.fundamental" xreflabel="Fundamental Types"><info><title>Fundamental Types</title></info>
     31 
     32     <para>
     33       C++ has the following builtin types:
     34     </para>
     35     <itemizedlist>
     36       <listitem><para>
     37 	char
     38       </para></listitem>
     39       <listitem><para>
     40 	signed char
     41       </para></listitem>
     42       <listitem><para>
     43 	unsigned char
     44       </para></listitem>
     45       <listitem><para>
     46 	signed short
     47       </para></listitem>
     48       <listitem><para>
     49 	signed int
     50       </para></listitem>
     51       <listitem><para>
     52 	signed long
     53       </para></listitem>
     54       <listitem><para>
     55 	unsigned short
     56       </para></listitem>
     57       <listitem><para>
     58 	unsigned int
     59       </para></listitem>
     60       <listitem><para>
     61 	unsigned long
     62       </para></listitem>
     63       <listitem><para>
     64 	bool
     65       </para></listitem>
     66       <listitem><para>
     67 	wchar_t
     68       </para></listitem>
     69       <listitem><para>
     70 	float
     71       </para></listitem>
     72       <listitem><para>
     73 	double
     74       </para></listitem>
     75       <listitem><para>
     76 	long double
     77       </para></listitem>
     78     </itemizedlist>
     79 
     80     <para>
     81       These fundamental types are always available, without having to
     82       include a header file. These types are exactly the same in
     83       either C++ or in C.
     84     </para>
     85 
     86     <para>
     87       Specializing parts of the library on these types is prohibited:
     88       instead, use a POD.
     89     </para>
     90 
     91   </section>
     92   <section xml:id="std.support.types.numeric_limits" xreflabel="Numeric Properties"><info><title>Numeric Properties</title></info>
     93 
     94     <para>
     95     The header <filename class="headerfile">&lt;limits&gt;</filename> defines
     96     traits classes to give access to various implementation
     97     defined-aspects of the fundamental types. The traits classes --
     98     fourteen in total -- are all specializations of the class template
     99     <classname>numeric_limits</classname>
    100     and defined as follows:
    101     </para>
    102 
    103    <programlisting>
    104    template&lt;typename T&gt;
    105      struct class
    106      {
    107        static const bool is_specialized;
    108        static T max() throw();
    109        static T min() throw();
    110 
    111        static const int digits;
    112        static const int digits10;
    113        static const bool is_signed;
    114        static const bool is_integer;
    115        static const bool is_exact;
    116        static const int radix;
    117        static T epsilon() throw();
    118        static T round_error() throw();
    119 
    120        static const int min_exponent;
    121        static const int min_exponent10;
    122        static const int max_exponent;
    123        static const int max_exponent10;
    124 
    125        static const bool has_infinity;
    126        static const bool has_quiet_NaN;
    127        static const bool has_signaling_NaN;
    128        static const float_denorm_style has_denorm;
    129        static const bool has_denorm_loss;
    130        static T infinity() throw();
    131        static T quiet_NaN() throw();
    132        static T denorm_min() throw();
    133 
    134        static const bool is_iec559;
    135        static const bool is_bounded;
    136        static const bool is_modulo;
    137 
    138        static const bool traps;
    139        static const bool tinyness_before;
    140        static const float_round_style round_style;
    141      };
    142    </programlisting>
    143   </section>
    144 
    145   <section xml:id="std.support.types.null" xreflabel="NULL"><info><title>NULL</title></info>
    146 
    147     <para>
    148      The only change that might affect people is the type of
    149      <constant>NULL</constant>: while it is required to be a macro,
    150      the definition of that macro is <emphasis>not</emphasis> allowed
    151      to be an expression with pointer type such as
    152      <constant>(void*)0</constant>, which is often used in C.
    153     </para>
    154 
    155     <para>
    156      For <command>g++</command>, <constant>NULL</constant> is
    157      <code>#define</code>'d to be
    158      <constant>__null</constant>, a magic keyword extension of
    159      <command>g++</command> that is slightly safer than a plain integer.
    160     </para>
    161 
    162     <para>
    163      The biggest problem of #defining <constant>NULL</constant> to be
    164      something like <quote>0L</quote> is that the compiler will view
    165      that as a long integer before it views it as a pointer, so
    166      overloading won't do what you expect. It might not even have the
    167      same size as a pointer, so passing <constant>NULL</constant> to a
    168      varargs function where a pointer is expected might not even work
    169      correctly if <code>sizeof(NULL) &lt; sizeof(void*)</code>.
    170      The G++ <constant>__null</constant> extension is defined so that
    171      <code>sizeof(__null) == sizeof(void*)</code> to avoid this problem.
    172     </para>
    173 
    174     <para>
    175      Scott Meyers explains this in more detail in his book
    176      <link xmlns:xlink="http://www.w3.org/1999/xlink"
    177       xlink:href="https://www.aristeia.com/books.html"><emphasis>Effective
    178      Modern C++</emphasis></link> and as a guideline to solve this problem
    179      recommends to not overload on pointer-vs-integer types to begin with.
    180     </para>
    181 
    182     <para>
    183      The C++ 2011 standard added the <constant>nullptr</constant> keyword,
    184      which is a null pointer constant of a special type,
    185      <classname>std::nullptr_t</classname>. Values of this type can be
    186      implicitly converted to <emphasis>any</emphasis> pointer type,
    187      and cannot convert to integer types or be deduced as an integer type.
    188      Unless you need to be compatible with C++98/C++03 or C you should prefer
    189      to use <constant>nullptr</constant>  instead of <constant>NULL</constant>.
    190     </para>
    191   </section>
    192 
    193 </section>
    194 
    195 <section xml:id="std.support.memory" xreflabel="Dynamic Memory"><info><title>Dynamic Memory</title></info>
    196   <?dbhtml filename="dynamic_memory.html"?>
    197 
    198   <para>
    199     In C++98 there are six flavors each of <function>operator new</function>
    200     and <function>operator delete</function>, so make certain that you're
    201     using the right ones.
    202     Here are quickie descriptions of <function>operator new</function>:
    203   </para>
    204   <variablelist>
    205     <varlistentry>
    206       <term><code>void* operator new(std::size_t);</code></term>
    207       <listitem>
    208 	Single object form.
    209         Throws <classname>std::bad_alloc</classname> on error.
    210         This is what most people are used to using.
    211       </listitem>
    212     </varlistentry>
    213     <varlistentry>
    214       <term><code>void* operator new(std::size_t, std::nothrow_t) noexcept;</code></term>
    215       <listitem>
    216 	Single object <quote>nothrow</quote> form.
    217         Calls <code>operator new(std::size_t)</code> but if that throws,
    218         returns a null pointer instead.
    219       </listitem>
    220     </varlistentry>
    221     <varlistentry>
    222       <term><code>void* operator new[](std::size_t);</code></term>
    223       <listitem>
    224 	Array <function>new</function>.
    225         Calls <code>operator new(std::size_t)</code> and so
    226 	throws <classname>std::bad_alloc</classname> on error.
    227       </listitem>
    228     </varlistentry>
    229     <varlistentry>
    230       <term><code>void* operator new[](std::size_t, std::nothrow_t) noexcept;</code></term>
    231       <listitem>
    232 	Array <quote>nothrow</quote> <function>new</function>.
    233         Calls <code>operator new[](std::size_t)</code> but if that throws,
    234         returns a null pointer instead.
    235       </listitem>
    236     </varlistentry>
    237     <varlistentry>
    238       <term><code>void* operator new(std::size_t, void*) noexcept;</code></term>
    239       <listitem>
    240 	Non-allocating, <quote>placement</quote> single-object <function>new</function>,
    241         which does nothing except return its argument.
    242         This function cannot be replaced.
    243       </listitem>
    244     </varlistentry>
    245     <varlistentry>
    246       <term><code>void* operator new[](std::size_t, void*) noexcept;</code></term>
    247       <listitem>
    248 	Non-allocating, <quote>placement</quote> array <function>new</function>,
    249         which also does nothing except return its argument.
    250         This function cannot be replaced.
    251       </listitem>
    252     </varlistentry>
    253    </variablelist>
    254    <para>
    255      They are distinguished by the arguments that you pass to them, like
    256      any other overloaded function.  The six flavors of
    257      <function>operator delete</function>
    258      are distinguished the same way, but none of them are allowed to throw
    259      an exception under any circumstances anyhow.  (The overloads match up
    260      with the ones above, for completeness' sake.)
    261    </para>
    262    <para>
    263      The C++ 2014 revision of the standard added two additional overloads of
    264      <function>operator delete</function> for <quote>sized deallocation</quote>,
    265      allowing the compiler to provide the size of the storage being freed.
    266    </para>
    267    <para>
    268      The C++ 2017 standard added even more overloads of both
    269      <function>operator new</function> and <function>operator delete</function>
    270      for allocating and deallocating storage for overaligned types.
    271      These overloads correspond to each of the allocating forms of
    272      <function>operator new</function> and <function>operator delete</function>
    273      but with an additional parameter of type <type>std::align_val_t</type>.
    274      These new overloads are not interchangeable with the versions without
    275      an aligment parameter, so if memory was allocated by an overload of
    276      <function>operator new</function> taking an alignment parameter,
    277      then it must be decallocated by the corresponding overload of
    278      <function>operator delete</function> that takes an alignment parameter.
    279    </para>
    280    <para>
    281      Apart from the non-allocating forms, the default versions of the array
    282      and nothrow <function>operator new</function> functions will all result
    283      in a call to either <function>operator new(std::size_t)</function> or
    284      <function>operator new(std::size_t, std::align_val_t)</function>,
    285      and similarly the default versions of the array and nothrow
    286      <function>operator delete</function> functions will result in a call to
    287      either <function>operator delete(void*)</function> or
    288      <function>operator delete(void*, std::align_val_t)</function>
    289      (or the sized versions of those).
    290    </para>
    291    <para>
    292      Apart from the non-allocating forms, any of these functions can be
    293      replaced by defining a function with the same signature in your program.
    294      Replacement versions must preserve certain guarantees, such as memory
    295      obtained from a nothrow <function>operator new</function> being free-able
    296      by the normal (non-nothrow) <function>operator delete</function>,
    297      and the sized and unsized forms of <function>operator delete</function>
    298      being interchangeable (because it's unspecified whether
    299      the compiler calls the sized delete instead of the normal one).
    300      The simplest way to meet the guarantees is to only replace the ordinary
    301      <function>operator new(size_t)</function> and
    302      <function>operator delete(void*)</function> and
    303      <function>operator delete(void*, std::size_t)</function>
    304      functions, and the replaced versions will be used by all of
    305      <function>operator new(size_t, nothrow_t)</function>,
    306      <function>operator new[](size_t)</function> and
    307      <function>operator new[](size_t, nothrow_t)</function>
    308      and the corresponding <function>operator delete</function> functions.
    309      To support types with extended alignment you may also need to replace
    310      <function>operator new(size_t, align_val_t)</function> and
    311      <function>operator delete(void*, align_val_t)</function>
    312      <function>operator delete(void*, size_t, align_val_t)</function>
    313      (which will then be used by the nothrow and array forms for
    314      extended alignments).
    315      If you do need to replace other forms (e.g. to define the nothrow
    316      <function>operator new</function> to allocate memory directly, so it
    317      works with exceptions disabled) then make sure the memory it allocates
    318      can still be freed by the non-nothrow forms of
    319      <function>operator delete</function>.
    320    </para>
    321    <para>
    322      If the default versions of <function>operator new(std::size_t)</function>
    323      and <function>operator new(size_t, std::align_val_t)</function>
    324      can't allocate the memory requested, they usually throw an exception
    325      object of type <classname>std::bad_alloc</classname> (or some class
    326      derived from that). However, the program can influence that behavior
    327      by registering a <quote>new-handler</quote>, because what
    328      <function>operator new</function> actually does is something like:
    329    </para>
    330    <programlisting>
    331     while (true)
    332     {
    333       if (void* p = /* try to allocate memory */)
    334         return p;
    335       else if (std::new_handler h = std::get_new_handler ())
    336         h ();
    337       else
    338         throw bad_alloc{};
    339     }
    340    </programlisting>
    341    <para>
    342      This means you can influence what happens on allocation failure by
    343      writing your own new-handler and then registering it with
    344      <function>std::set_new_handler</function>:
    345    </para>
    346    <programlisting>
    347    typedef void (*PFV)();
    348 
    349    static char*  safety;
    350    static PFV    old_handler;
    351 
    352    void my_new_handler ()
    353    {
    354        delete[] safety;
    355        safety = nullptr;
    356        popup_window ("Dude, you are running low on heap memory.  You"
    357 		     " should, like, close some windows, or something."
    358 		     " The next time you run out, we're gonna burn!");
    359        set_new_handler (old_handler);
    360        return;
    361    }
    362 
    363    int main ()
    364    {
    365        safety = new char[500000];
    366        old_handler = set_new_handler (&amp;my_new_handler);
    367        ...
    368    }
    369    </programlisting>
    370 
    371    <section xml:id="std.support.memory.notes" xreflabel="Dynamic Memory Notes"><info><title>Additional Notes</title></info>
    372 
    373    <para>
    374      Remember that it is perfectly okay to <function>delete</function> a
    375      null pointer!  Nothing happens, by definition.  That is not the
    376      same thing as deleting a pointer twice.
    377    </para>
    378    <para>
    379      <classname>std::bad_alloc</classname> is derived from the base
    380      <classname>std::exception</classname> class,
    381      see <xref linkend="std.diagnostics.exceptions"/>.
    382    </para>
    383    </section>
    384 
    385 </section>
    386 
    387 <section xml:id="std.support.termination" xreflabel="Termination"><info><title>Termination</title></info>
    388   <?dbhtml filename="termination.html"?>
    389 
    390   <section xml:id="support.termination.handlers" xreflabel="Termination Handlers"><info><title>Termination Handlers</title></info>
    391 
    392     <para>
    393       Not many changes here to
    394       <filename class="headerfile">&lt;cstdlib&gt;</filename>.
    395       You should note that the
    396       <function>abort()</function> function does not call the
    397       destructors of automatic nor static objects, so if you're
    398       depending on those to do cleanup, it isn't going to happen.
    399       (The functions registered with <function>atexit()</function>
    400       don't get called either, so you can forget about that
    401       possibility, too.)
    402     </para>
    403     <para>
    404       The good old <function>exit()</function> function can be a bit
    405       funky, too, until you look closer.  Basically, three points to
    406       remember are:
    407     </para>
    408     <orderedlist inheritnum="ignore" continuation="restarts">
    409       <listitem>
    410 	<para>
    411 	Static objects are destroyed in reverse order of their creation.
    412 	</para>
    413       </listitem>
    414       <listitem>
    415 	<para>
    416 	Functions registered with <function>atexit()</function> are called in
    417 	reverse order of registration, once per registration call.
    418 	(This isn't actually new.)
    419 	</para>
    420       </listitem>
    421       <listitem>
    422 	<para>
    423 	The previous two actions are <quote>interleaved,</quote> that is,
    424 	given this pseudocode:
    425 	</para>
    426 <programlisting>
    427   extern "C or C++" void f1 ();
    428   extern "C or C++" void f2 ();
    429 
    430   static Thing obj1;
    431   atexit(f1);
    432   static Thing obj2;
    433   atexit(f2);
    434 </programlisting>
    435 	<para>
    436 	then at a call of <function>exit()</function>,
    437 	<varname>f2</varname> will be called, then
    438 	<varname>obj2</varname> will be destroyed, then
    439 	<varname>f1</varname> will be called, and finally
    440 	<varname>obj1</varname> will be destroyed. If
    441 	<varname>f1</varname> or <varname>f2</varname> allow an
    442 	exception to propagate out of them, Bad Things happen.
    443 	</para>
    444       </listitem>
    445     </orderedlist>
    446     <para>
    447       Note also that <function>atexit()</function> is only required to store 32
    448       functions, and the compiler/library might already be using some of
    449       those slots.  If you think you may run out, we recommend using
    450       the <function>xatexit</function>/<function>xexit</function> combination
    451       from <literal>libiberty</literal>, which has no such limit.
    452     </para>
    453   </section>
    454 
    455   <section xml:id="support.termination.verbose" xreflabel="Verbose Terminate Handler"><info><title>Verbose Terminate Handler</title></info>
    456   <?dbhtml filename="verbose_termination.html"?>
    457 
    458     <para>
    459       If you are having difficulty with uncaught exceptions and want a
    460       little bit of help debugging the causes of the core dumps, you can
    461       make use of a GNU extension, the verbose terminate handler.
    462     </para>
    463 
    464     <para>
    465       The verbose terminate handler is only available for hosted environments
    466       (see <xref linkend="manual.intro.setup.configure"/>) and will be used
    467       by default unless the library is built with
    468       <option>--disable-libstdcxx-verbose</option>
    469       or with exceptions disabled.
    470       If you need to enable it explicitly you can do so by calling the
    471       <function>std::set_terminate</function> function.
    472     </para>
    473 
    474 <programlisting>
    475 #include &lt;exception&gt;
    476 
    477 int main()
    478 {
    479   std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
    480   ...
    481 
    482   throw <replaceable>anything</replaceable>;
    483 }
    484 </programlisting>
    485 
    486    <para>
    487      The <function>__verbose_terminate_handler</function> function
    488      obtains the name of the current exception, attempts to demangle
    489      it, and prints it to <literal>stderr</literal>.
    490      If the exception is derived from
    491      <classname>std::exception</classname> then the output from
    492      <function>what()</function> will be included.
    493    </para>
    494 
    495    <para>
    496      Any replacement termination function is required to kill the
    497      program without returning; this one calls <function>std::abort</function>.
    498    </para>
    499 
    500    <para>
    501      For example:
    502    </para>
    503 
    504 <programlisting>
    505 #include &lt;exception&gt;
    506 #include &lt;stdexcept&gt;
    507 
    508 struct argument_error : public std::runtime_error
    509 {
    510   argument_error(const std::string&amp; s): std::runtime_error(s) { }
    511 };
    512 
    513 int main(int argc)
    514 {
    515   std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
    516   if (argc &gt; 5)
    517     throw argument_error("argc is greater than 5!");
    518   else
    519     throw argc;
    520 }
    521 </programlisting>
    522 
    523    <para>
    524      With the verbose terminate handler active, this gives:
    525    </para>
    526 
    527    <screen>
    528    <computeroutput>
    529    % ./a.out
    530    terminate called after throwing a `int'
    531    Aborted
    532    % ./a.out f f f f f f f f f f f
    533    terminate called after throwing an instance of `argument_error'
    534    what(): argc is greater than 5!
    535    Aborted
    536    </computeroutput>
    537    </screen>
    538 
    539    <para>
    540      The 'Aborted' line is printed by the shell after the process exits
    541      by calling <function>abort()</function>.
    542    </para>
    543 
    544    <para>
    545      As this is the default termination handler, nothing need be done to
    546      use it.  To go back to the previous <quote>silent death</quote>
    547      method, simply include
    548      <filename class="headerfile">&lt;exception&gt;</filename> and
    549      <filename class="headerfile">&lt;cstdlib&gt;</filename>, and call
    550    </para>
    551 
    552    <programlisting>
    553      std::set_terminate(std::abort);
    554    </programlisting>
    555 
    556    <para>
    557      After this, all calls to <function>terminate</function> will use
    558      <function>abort</function> as the terminate handler.
    559    </para>
    560 
    561    <para>
    562      Note: the verbose terminate handler will attempt to write to
    563      <literal>stderr</literal>.  If your application closes
    564      <literal>stderr</literal> or redirects it to an inappropriate location,
    565      <function>__verbose_terminate_handler</function> will behave in
    566      an unspecified manner.
    567    </para>
    568 
    569   </section>
    570 </section>
    571 
    572 </chapter>
    573