The operator new
allocates memory for objects, and the operator delete
frees the memory allocated by the matching
operator new
. When a class needs to customize memory allocation, it can override the operator new
to use a custom memory
allocation strategy and override the operator delete
accordingly.
If the operator delete
is not overridden alongside the operator new
, the program will call its default implementation,
which may not be suitable for the custom memory allocation strategy used by the overridden operator new
.
For instance, if the operator new
draws memory from a preallocated buffer instead of allocating memory, the operator
delete
should not call the free
function to release the memory. Reciprocally, if the operator new
allocate memory
with malloc
, the operator delete
must call free
.
On the other hand, if the operator delete
is overridden without overriding the operator new
, it is suspicious because it
may not correctly release the memory allocated by the default operator new
.
By defining the operator delete
along with the operator new
, the memory is deallocated in a way consistent with the
custom allocation strategy used by the operator new
.
What is the potential impact?
Overriding only one of the two operators may result in your program consuming more and more memory over time, eventually leading to a crash.
Deallocating memory that was not allocated with the corresponding strategy results in undefined behavior.