By Renan Campos
When to overload new/delete and why Requirements of the implementing “new” Implementing “array new” Implementing the “delete” operator Summary Example Code Questions
To detect usage errors To collect statistics about the use of dynamically allocated memory To increase the speed of allocation and deallocation To reduce the space overhead of default memory management To componsate for suboptimal alignment in the default allocation To cluster related objects near one another To obtain unconventional behavior
The new operator requires: 1. The right return value 2. Calling the new-handling function when insufficient memory is available 3. Being prepared to cope with requests for no memory 4. Avoiding hiding the normal form of new (See item 52) 5. Handle inherited classes
Just allocate a chunk of raw memory.
void operator delete( void* rawMem ) throw() { if ( rawMem == 0 ) return ; // deallocate the memory pointed }
For new: Operator new should contain an infinite loop trying to allocate memory. New_handler should be called if memory request failed. Class-specific versions should handle requests for larger blocks than expected. For delete: Operator delete should do nothing if given a null pointer. Class-specific versions should handle requests for larger blocks than expected.