Dynamic Memory
Prev | Chapter 4. Support | Next

## Dynamic Memory

There are six flavors each of `new` and `delete`, so make certain that you're using the right ones. Here are quickie descriptions of `new`:

- single object form, throwing a `bad_alloc` on errors; this is what most people are used to using

- Single object "nothrow" form, returning NULL on errors

- Array `new`, throwing `bad_alloc` on errors

- Array nothrow `new`, returning `NULL` on errors

- Placement `new`, which does nothing (like it's supposed to)

- Placement array `new`, which also does nothing

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

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

By default, if one of the “throwing `new`s” can't allocate the memory requested, it tosses an instance of a `bad_alloc` exception (or, technically, some class derived from it). You can change this by writing your own function (called a new-handler) and then registering it with `set_new_handler()`:

       typedef void (*PFV)(void);

       static char*  safety;
       static PFV    old_handler;

       void my_new_handler ()
       {
           delete[] safety;
           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);
           ...
       }

`bad_alloc` is derived from the base `exception` class defined in Sect1 19.

Prev | Up | Next
Chapter 4. Support | Home | Termination