Overload new and delete operator

new operator allocates the memory then calls the constructor. delete operator calls the destructor then delete the memory.

As these are operators, so it can be overloaded. But why we need to overload these operators.
* In case, there is lot of allocation and deallocation happens from the heap memory, it can affect the performance. So, to overcome this, we overload the new and delete operator.
* Also, as part of above scenario, heap memory gets fragmented. As a result, even though there is sufficient memory present in heap, still it is not able to give because those memory are not contiguous. To avoid this situation, we overload new and delete operator.

new and delete operator overloading can be done at class as well as global level.

Overload new operator
Takes an argument of type size_t. The value will be calculated automatically by the compiler as per the object size and passed to this argument.

Return type is the void pointer to allocated memory or zero if there is no memory allocated.

Overload delete operator
delete operator takes void pointer as an argument which is pointer to memory allocated by new operator. The reason of having void pointer is because object destructor is called before deallocating the memory, so only memory parts need to be deallocated.

Return type is void

Below is the code snippet for operator overloading of new and delete operator

 

void* operator new(size_t sz) {
    void* ptr = malloc(sz);
    if (NULL == ptr) {
        cout << “No Free memory is available” << endl;
    }
    return ptr;
}
void operator delete(void* ptr) {
    cout << “Free Memory” << endl;
    free(ptr);
}

Above funtions are globally overloaded version of new and delete operator. Same function can be used at class level as well.

  • Once you overload the new and delete operator globally, then default definition of them will not be available for you and not even inside your overloaded definition
  • Once you overload the new and delete operator, you should replace the behavior when its run out of memory
  • In case overloaded new operator cannot allocate memory, then instead of just returning zero, try to throw an exception to tell the user that memory is exhausted
  • If the new and delete operator is overloaded for a class , then it will take higher precedence over global version when new and delete is performed for that particular class. For other classes or primitive data types,  global is used.
  • Globally overloaded new and delete operator is used for primitive data types as well.
  • Overloaded new and delete operator in a class are static member functions even though you don’t declare it as static.

Related posts