By Renan Campos. When to overload new/delete and why Requirements of the implementing “new” ...
-
Upload
albert-mccarthy -
Category
Documents
-
view
212 -
download
0
Transcript of By Renan Campos. When to overload new/delete and why Requirements of the implementing “new” ...
ITEM 51: ADHERE TO CONVENTION WHEN
WRITING NEW AND DELETE
By Renan Campos
OVERVIEW When to overload new/delete and why Requirements of the implementing
“new” Implementing “array new” Implementing the “delete” operator Summary Example Code Questions
WHEN AND WHY (ITEM 50) 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
IMPLEMENTING NEWThe new operator requires:1. The right return value2. Calling the new-handling function
when insufficient memory is available3. Being prepared to cope with requests
for no memory4. Avoiding hiding the normal form of
new (See item 52)5. Handle inherited classes
IMPLEMENTING NEW[]
Just allocate a chunk of raw memory.
IMPLEMENTING DELETEvoid operator delete( void* rawMem ) throw() {
if ( rawMem == 0 ) return ;
// deallocate the memory pointed
}
SUMMARYFor 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.
SAMPLE CODE
QUESTIONS?