Ejemplo: Redefinición del operador nuevo o de supresión

Solo lenguaje C++ Para crear módulos que asignen almacenamiento dinámicamente desde teraespacio, especifique TERASPACE (*YES *TSIFC) en los mandatos CRTCPPMOD y CRTBNDCPP. Esto vuelve a correlacionar las funciones de tiempo de ejecución C (como malloc, calloc y free) con nuevos equivalentes de teraespacio. Esto también afecta al almacenamiento asignado dinámicamente utilizando los operadores new y delete . Si desea que los operadores new y delete asignen almacenamiento de otro modo, puede alterar temporalmente estos operadores.

El código siguiente redefine los operadores new y delete globales para llamar a funciones (como malloc o free).

Nota: Para encontrar la declaración de _set_mt_new_handler, el siguiente origen debe compilarse con DEFINE ('__MULTI__').
Figura 1. Ejemplo de código fuente que redefine los operadores nuevos y de supresión globales.
  #include <stdlib.h>
  #include <new>

  using namespace std;
  void *operator new(size_t size) throw (bad_alloc)
  {
    // if size == 0, we must return a valid object! (ARM 5.3.3)
    if (size <= 0)
        size = 1;
 
    void *ret = (malloc)(size);
 
    while (ret == NULL)
    {
          // The malloc failed.  Call the new_handler to try to free more memory
          void (*temp_new_handler)();
 
          // First check to see if a thread local new handler is defined.
          temp_new_handler = _set_mt_new_handler(0);
          _set_mt_new_handler(temp_new_handler);
 
          // If there is no thread local handler try the global handler.
          if (temp_new_handler == NULL)
          {
              // Note that the following code is not thread safe
              // If the application is threaded and a new handler is set then
              // all calls to set_new_handler() in the application must be
              // blocked.  Otherwise for the sake of speed, do not use a locking
              // mechanism.
 
              temp_new_handler = set_new_handler(0);
              set_new_handler(temp_new_handler);
          }
 
          if (temp_new_handler != NULL)
          {
              temp_new_handler();
 
              // Try one more time
              ret = (malloc)(size);
          }
         else
              throw bad_alloc();    
      }
 
      // just return the result to the user
      return ret;
  }

  void operator delete(void *ptr)
  {
      // delete of NULL is okay
      if (ptr == NULL)
          return;
 
      (free)(ptr);
  }