C++ <new> Library - set_new_handler



Description

It is used to set new handler function and the new-handler function is a function which is called by the default allocation functions (operator new and operator new[]) when they fail to allocate storage.

Declaration

Following is the declaration for std::set_new_handler.

		
new_handler set_new_handler (new_handler new_p) throw();

C++11

			
new_handler set_new_handler (new_handler new_p) noexcept;

Parameters

new_p − Function that takes no arguments and returns no value.

Return Value

It returns the value of the current new-handler function.

Exceptions

No-throw guarantee − this function never throws exceptions.

Data races

Calling this function does not introduce data races.

Example

In below example explains about std::set_new_handler.

#include <iostream>
#include <cstdlib>
#include <new>

void no_memory () {
   std::cout << "Failed to allocate memory!\n";
   std::exit (1);
}

int main () {
   std::set_new_handler(no_memory);
   std::cout << "Attempting to allocate...";
   char* p = new char [1024];
   std::cout << "Ok\n";
   delete[] p;
   return 0;
}

Let us compile and run the above program, this will produce the following result −

Attempting to allocate...Ok
new.htm
Advertisements