# Support

Support
ISO C++ library

This part deals with the functions called and objects created automatically during the course of a program's existence.

While we can't reproduce the contents of the Standard here (you need to get your own copy from your nation's member body; see our homepage for help), we can mention a couple of changes in what kind of support a C++ program gets from the Standard Library.

## Types

### Fundamental Types

C++ has the following builtin types:

- char

- signed char

- unsigned char

- signed short

- signed int

- signed long

- unsigned short

- unsigned int

- unsigned long

- bool

- wchar_t

- float

- double

- long double

These fundamental types are always available, without having to include a header file. These types are exactly the same in either C++ or in C.

Specializing parts of the library on these types is prohibited: instead, use a POD.

### Numeric Properties

The header `<limits>` defines traits classes to give access to various implementation defined-aspects of the fundamental types. The traits classes -- fourteen in total -- are all specializations of the class template numeric_limits and defined as follows:

       template<typename T>
         struct class
         {
           static const bool is_specialized;
           static T max() throw();
           static T min() throw();

           static const int digits;
           static const int digits10;
           static const bool is_signed;
           static const bool is_integer;
           static const bool is_exact;
           static const int radix;
           static T epsilon() throw();
           static T round_error() throw();

           static const int min_exponent;
           static const int min_exponent10;
           static const int max_exponent;
           static const int max_exponent10;

           static const bool has_infinity;
           static const bool has_quiet_NaN;
           static const bool has_signaling_NaN;
           static const float_denorm_style has_denorm;
           static const bool has_denorm_loss;
           static T infinity() throw();
           static T quiet_NaN() throw();
           static T denorm_min() throw();

           static const bool is_iec559;
           static const bool is_bounded;
           static const bool is_modulo;

           static const bool traps;
           static const bool tinyness_before;
           static const float_round_style round_style;
         };

### NULL

The only change that might affect people is the type of `NULL`: while it is required to be a macro, the definition of that macro is not allowed to be an expression with pointer type such as `(void*)0`, which is often used in C.

For `g++`, `NULL` is `#define`'d to be `__null`, a magic keyword extension of `g++` that is slightly safer than a plain integer.

The biggest problem of #defining `NULL` to be something like 0L is that the compiler will view that as a long integer before it views it as a pointer, so overloading won't do what you expect. It might not even have the same size as a pointer, so passing `NULL` to a varargs function where a pointer is expected might not even work correctly if `sizeof(NULL) < sizeof(void*)`. The G++ `__null` extension is defined so that `sizeof(__null) == sizeof(void*)` to avoid this problem.

Scott Meyers explains this in more detail in his book Effective Modern C++ and as a guideline to solve this problem recommends to not overload on pointer-vs-integer types to begin with.

The C++ 2011 standard added the `nullptr` keyword, which is a null pointer constant of a special type, std::nullptr_t. Values of this type can be implicitly converted to any pointer type, and cannot convert to integer types or be deduced as an integer type. Unless you need to be compatible with C++98/C++03 or C you should prefer to use `nullptr` instead of `NULL`.

## Dynamic Memory

In C++98 there are six flavors each of `operator new` and `operator delete`, so make certain that you're using the right ones. Here are quickie descriptions of `operator new`:

`void* operator new(std::size_t);`
  Single object form. Throws std::bad_alloc on error. This is what most people are used to using.
`void* operator new(std::size_t, std::nothrow_t) noexcept;`
  Single object nothrow form. Calls `operator new(std::size_t)` but if that throws, returns a null pointer instead.
`void* operator new[](std::size_t);`
  Array `new`. Calls `operator new(std::size_t)` and so throws std::bad_alloc on error.
`void* operator new[](std::size_t, std::nothrow_t) noexcept;`
  Array nothrow `new`. Calls `operator new[](std::size_t)` but if that throws, returns a null pointer instead.
`void* operator new(std::size_t, void*) noexcept;`
  Non-allocating, placement single-object `new`, which does nothing except return its argument. This function cannot be replaced.
`void* operator new[](std::size_t, void*) noexcept;`
  Non-allocating, placement array `new`, which also does nothing except return its argument. This function cannot be replaced.

They are distinguished by the arguments that you pass to them, like any other overloaded function. The six flavors of `operator delete` are distinguished the same way, but none of them are allowed to throw an exception under any circumstances anyhow. (The overloads match up with the ones above, for completeness' sake.)

The C++ 2014 revision of the standard added two additional overloads of `operator delete` for sized deallocation, allowing the compiler to provide the size of the storage being freed.

The C++ 2017 standard added even more overloads of both `operator new` and `operator delete` for allocating and deallocating storage for overaligned types. These overloads correspond to each of the allocating forms of `operator new` and `operator delete` but with an additional parameter of type std::align_val_t. These new overloads are not interchangeable with the versions without an aligment parameter, so if memory was allocated by an overload of `operator new` taking an alignment parameter, then it must be decallocated by the corresponding overload of `operator delete` that takes an alignment parameter.

Apart from the non-allocating forms, the default versions of the array and nothrow `operator new` functions will all result in a call to either `operator new(std::size_t)` or `operator new(std::size_t, std::align_val_t)`, and similarly the default versions of the array and nothrow `operator delete` functions will result in a call to either `operator delete(void*)` or `operator delete(void*, std::align_val_t)` (or the sized versions of those).

Apart from the non-allocating forms, any of these functions can be replaced by defining a function with the same signature in your program. Replacement versions must preserve certain guarantees, such as memory obtained from a nothrow `operator new` being free-able by the normal (non-nothrow) `operator delete`, and the sized and unsized forms of `operator delete` being interchangeable (because it's unspecified whether the compiler calls the sized delete instead of the normal one). The simplest way to meet the guarantees is to only replace the ordinary `operator new(size_t)` and `operator delete(void*)` and `operator delete(void*, std::size_t)` functions, and the replaced versions will be used by all of `operator new(size_t, nothrow_t)`, `operator new[](size_t)` and `operator new[](size_t, nothrow_t)` and the corresponding `operator delete` functions. To support types with extended alignment you may also need to replace `operator new(size_t, align_val_t)` and `operator delete(void*, align_val_t)` `operator delete(void*, size_t, align_val_t)` (which will then be used by the nothrow and array forms for extended alignments). If you do need to replace other forms (e.g. to define the nothrow `operator new` to allocate memory directly, so it works with exceptions disabled) then make sure the memory it allocates can still be freed by the non-nothrow forms of `operator delete`.

If the default versions of `operator new(std::size_t)` and `operator new(size_t, std::align_val_t)` can't allocate the memory requested, they usually throw an exception object of type std::bad_alloc (or some class derived from that). However, the program can influence that behavior by registering a new-handler, because what `operator new` actually does is something like:

        while (true)
        {
          if (void* p = /* try to allocate memory */)
            return p;
          else if (std::new_handler h = std::get_new_handler ())
            h ();
          else
            throw bad_alloc{};
        }

This means you can influence what happens on allocation failure by writing your own new-handler and then registering it with `std::set_new_handler`:

       typedef void (*PFV)();

       static char*  safety;
       static PFV    old_handler;

       void my_new_handler ()
       {
           delete[] safety;
           safety = nullptr;
           popup_window ("Dude, you are running low on heap memory.  You"
    		     " should, like, close some windows, or something."
    		     " The next time you run out, we're gonna burn!");
           set_new_handler (old_handler);
           return;
       }

       int main ()
       {
           safety = new char[500000];
           old_handler = set_new_handler (&my_new_handler);
           ...
       }

### Additional Notes

Remember that it is perfectly okay to `delete` a null pointer! Nothing happens, by definition. That is not the same thing as deleting a pointer twice.

std::bad_alloc is derived from the base std::exception class, see .

## Termination

### Termination Handlers

Not many changes here to `<cstdlib>`. You should note that the `abort()` function does not call the destructors of automatic nor static objects, so if you're depending on those to do cleanup, it isn't going to happen. (The functions registered with `atexit()` don't get called either, so you can forget about that possibility, too.)

The good old `exit()` function can be a bit funky, too, until you look closer. Basically, three points to remember are:

1. Static objects are destroyed in reverse order of their creation.

2. Functions registered with `atexit()` are called in reverse order of registration, once per registration call. (This isn't actually new.)

3. The previous two actions are interleaved, that is, given this pseudocode:

         extern "C or C++" void f1 ();
         extern "C or C++" void f2 ();

         static Thing obj1;
         atexit(f1);
         static Thing obj2;
         atexit(f2);

   then at a call of `exit()`, `f2` will be called, then `obj2` will be destroyed, then `f1` will be called, and finally `obj1` will be destroyed. If `f1` or `f2` allow an exception to propagate out of them, Bad Things happen.

Note also that `atexit()` is only required to store 32 functions, and the compiler/library might already be using some of those slots. If you think you may run out, we recommend using the `xatexit`/`xexit` combination from `libiberty`, which has no such limit.

### Verbose Terminate Handler

If you are having difficulty with uncaught exceptions and want a little bit of help debugging the causes of the core dumps, you can make use of a GNU extension, the verbose terminate handler.

The verbose terminate handler is only available for hosted environments (see ) and will be used by default unless the library is built with `--disable-libstdcxx-verbose` or with exceptions disabled. If you need to enable it explicitly you can do so by calling the `std::set_terminate` function.

    #include <exception>

    int main()
    {
      std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
      ...

      throw anything;
    }

The `__verbose_terminate_handler` function obtains the name of the current exception, attempts to demangle it, and prints it to `stderr`. If the exception is derived from std::exception then the output from `what()` will be included.

Any replacement termination function is required to kill the program without returning; this one calls `std::abort`.

For example:

    #include <exception>
    #include <stdexcept>

    struct argument_error : public std::runtime_error
    {
      argument_error(const std::string& s): std::runtime_error(s) { }
    };

    int main(int argc)
    {
      std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
      if (argc > 5)
        throw argument_error("argc is greater than 5!");
      else
        throw argc;
    }

With the verbose terminate handler active, this gives:

       % ./a.out
       terminate called after throwing a `int'
       Aborted
       % ./a.out f f f f f f f f f f f
       terminate called after throwing an instance of `argument_error'
       what(): argc is greater than 5!
       Aborted

The 'Aborted' line is printed by the shell after the process exits by calling `abort()`.

As this is the default termination handler, nothing need be done to use it. To go back to the previous silent death method, simply include `<exception>` and `<cstdlib>`, and call

         std::set_terminate(std::abort);

After this, all calls to `terminate` will use `abort` as the terminate handler.

Note: the verbose terminate handler will attempt to write to `stderr`. If your application closes `stderr` or redirects it to an inappropriate location, `__verbose_terminate_handler` will behave in an unspecified manner.