Chapter 5. 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:

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 news” 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 Chapter 19.