Lesson 15 | Overloading new and delete |
Objective | Overload operators new and delete |
Overloading new and delete in C++
Overload the operators new and delete to allow an object to utilize traditional C free store management.
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.
new Operator
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);
The operator new can also include placement syntax.
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.
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.
new-delete operators - Exercise
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