Freigeben über


set_new_handler

Installs a user function that is to be called when operator new fails in its attempt to allocate memory.

new_handler set_new_handler(
   new_handler _Pnew
) throw( );

Parameters

  • _Pnew
    The new_handler to be installed.

Return Value

0 on the first call and the previous new_handler on subsequent calls.

Remarks

The function stores _Pnew in a static new handler pointer that it maintains, then returns the value previously stored in the pointer. The new handler is used by operator new(size_t).

Example

// new_set_new_handler.cpp
// compile with: /EHsc
#include<new>
#include<iostream>

using namespace std;
void __cdecl newhandler( )
{
   cout << "The new_handler is called:" << endl;
   throw bad_alloc( );
   return;
}

int main( ) 
{
   set_new_handler (newhandler);
   try
   {
      while ( 1 ) 
      {
         new int[5000000];
         cout << "Allocating 5000000 ints." << endl;
      }
   }
   catch ( exception e )
   {
      cout << e.what( ) << endl;
   }
}
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
The new_handler is called:
bad allocation

Requirements

Header: <new>

Namespace: std

See Also

Other Resources

<new> Members