Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can "new_handler" be used for in C++ besides garbage collection?

C++ programs can define and set a new_handler() that should be called from memory allocation functions like operator new() if it's impossible to allocate memory requested.

One use of a custom new_handler() is dealing with C++ implementations that don't throw an exception on allocation failure. Another use is initiating garbage collection on systems that implement garbage collection.

What other uses of custom new_handler() are there?

like image 342
sharptooth Avatar asked Apr 05 '11 07:04

sharptooth


2 Answers

In a similar vein to the garbage collection application, you can use the new handler to free up any cached data you may be keeping.

Say that you're caching some resource data read from disk or the intermediate results of some calculation. This is data that you can recreate at any time, so when the new handler gets called (signifying that you've run out of heap), you can free the memory for the cached data, then return from the new handler. Hopefully, new will now be able to make the allocation.

In many cases, virtual memory can serve the same purpose: You can simply let your cached data get swapped out to disk -- if you've got enough virtual address space. On 32-bit systems, this isn't really the case any more, so the new handler is an interesting option. Many embedded systems will face similar constraints.

like image 75
Martin B Avatar answered Oct 21 '22 16:10

Martin B


On most of the servers I've worked on, the new_handler freed a pre-allocated block (so future new's wouldn't fail) before logging a message (the logger used dynamic memory) and aborting. This ensured that the out of memory error was correctly logged (instead of the process just "disappearing", with an error message to cerr, which was connected to /dev/null).

In applications such as editors, etc., it may be possible to spill parts of some buffers to disk, then continue; if the new_handler returns, operator new is supposed to retry the allocation, and if the new_handler has freed up enough memory, the allocation may succeed (and if it doesn't, the new_handler will be called again, to maybe free up even more).

like image 6
James Kanze Avatar answered Oct 21 '22 17:10

James Kanze