RAD Studio |  |

set_new_handler function

Header File

new.h

Category

Memory Routines

Syntax

typedef void (new * new_handler)();

new_handler set_new_handler(new_handler my_handler);

Description

set_new_handler installs the function to be called when the global operator new or operator new[]() cannot allocate the requested memory. By default the new operators throw an bad_alloc exception if memory cannot be allocated. You can change this default behavior by calling set_new_handler to set a new handler. To retain the traditional version of new, which does not throw exceptions, you can use set_new_handler(0).

If new cannot allocate the requested memory, it calls the handler that was set by a previous call to set_new_handler. If there is no handler installed by set_new_handler, new returns 0. my_handler should specify the actions to be taken when new cannot satisfy a request for memory allocation. The new_handler type, defined in new.h, is a function that takes no arguments and returns void. A new_handler can throw a bad_alloc exception.

- The user-defined my_handler should do one of the following:
- return after freeing memory
- throw an bad_alloc exception or an exception derived from bad_alloc
- call abort or exit functions

If my_handler returns, then new will again attempt to satisfy the request.

Ideally, my_handler would free up memory and return. new would then be able to satisfy the request and the program would continue. However, if my_handler cannot provide memory for new, my_handler must throw an exception or terminate the program. Otherwise, an infinite loop will be created.

Preferably, you should overload operator new() and operator new[]() to take appropriate actions for your applications.

Return Value

set_new_handler returns the old handler, if one has been registered.

The user-defined argument function, my_handler, should not return a value.

Example

Copy Code

    #include <iostream>
    #include <new.h>
    #include <stdlib.h>
    using std::cout;
    using std::hex;
    void mem_warn() {
      std::cerr << "\nCan't allocate!";
      exit(1);
    }

    void main(void) {
      std::set_new_handler(mem_warn);
      char *ptr = new char[100];
      cout << "\nFirst allocation: ptr = " << hex << long(ptr);
      ptr = new char[64000U];
      cout << "\nFinal allocation: ptr = " << hex << long(ptr);
      std::set_new_handler(0);  // Reset to default.
    }

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!