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

前端 未结 3 1231
半阙折子戏
半阙折子戏 2021-01-02 22:26

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 a

3条回答
  •  失恋的感觉
    2021-01-02 23:17

    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).

提交回复
热议问题