|
||
Lesson 15
Objective
|
Overloading new and delete Overload operators new and delete |
|
|
Overload the operators new and delete to allow an object to utilize traditional C free store management.
new Operator
Most classes involve free store memory allocation and deallocation. Most of the time, this is done through simple calls to operators new and delete. Sometimes, however, you may need a more sophisticated use of memory for efficiency or robustness. The operators new and delete can be overloaded.
One reason to overload these operators is to give them additional semantics, such as providing diagnostic information or making them
more fault tolerant. Also, the class can have a more efficient memory allocation scheme than provided by the system.
Up to now, we have been using the global operator new() to allocate free store. The system provides a sizeof(type) argument to this function implicitly. Its function prototype is void* operator new(size_t size); delete operator
The delete operator has two signatures, either of which can be overloaded:
void operator delete(void* p); void operator delete(void* p, size_t);
The first signature makes no provision for the number of bytes to be returned by delete. In this case, the programmer
provides code that supplies this value.
new-delete operators - Exercise The second signature includes a size_t argument passed to the delete invocation. This is provided by the compiler as the size of the object pointed at by p. Only one form of delete can be provided as a static member function in each class.
Click the Exercise link below to overload the operators new and delete to allow an object to utilize traditional C free
store management.
new-delete operators - Exercise |
||
|
|
||