For details, refer to Article 49 of the third edition of Objective C ++ to learn about new_handler's behavior.
Related links:
Http://blogold.chinaunix.net/u/3374/showart_1849816.html
When operator new fails to apply for a memory, it performs the following steps:
1. If a handler specified by the customer exists, call the handler (new_handler). If the handler does not exist, an exception is thrown.
2. Continue to apply for memory allocation requests.
3. Determine whether the memory application is successful. If the application is successful, the memory pointer is returned. If the application fails, the request is redirected to step 1.
To customize the new_handler function used to handle insufficient memory, you can call set_new_handler to set
The two functions are declared as follows:
Namespace STD {
Typedef void (* new_handler )();
New_handler set_new_handler (new_handler p) Throw ();
}
New_handler is a typedef that defines a function pointer. This function has no parameters or return values;
Set_new_handler is used to set the handler, Set P to the current handler, and return the previous new_handler.
When operator new cannot meet the memory allocation requirements, it will continuously call the new_handler function until enough memory is found.
Therefore, the new_handler function should be properly designed. A well-designed new_handler must do the following:
1. delete other useless memory so that the system can use more memory and prepare for the memory application.
The method to implement this policy is: The program allocates a large block of memory at the beginning of execution. When new_handler is called, it is released and used by the program.
2. Set another new_handler.
If the current new_handler cannot perform more memory application operations, or it knows that another new_handler can,
You can call the set_new_handler function to set another new_handler. In this way, during the next call of operator new,
You can use this new new_handler.
3. Uninstall new_handler and enable operator new to throw a memory application exception during the next call because new_handler is empty.
4. new_handler throws a custom exception.
5. If no response is returned, call abort or exit to exit the program.
C ++ does not support a specific type of new_handler, but if necessary, you can reload operator new to implement this behavior by yourself.
You only need to provide your own set_new_handler and operator new for the class.
Do the following in operator New:
1. First, call the standard set_new_handler to customize the processing functions of the exclusive class.
2. Call global operator new to execute the actual memory allocation. If the memory allocation fails, the newly installed new_handler will be called.
3. Whether New succeeds or fails, the global new_handler must be restored before the end of the class-defined operator new.
For detailed examples in this section, refer to Article 49 of Objective C ++.