New delete operator overloading in c++

A fundamental topic in C++!

In C++, the new and delete operators are used to dynamically allocate and deallocate memory. Overloading these operators allows you to customize the behavior of memory management for your classes.

Overloading new

To overload the new operator, you need to define a function called operator new in your class. This function should take two arguments: the size of the memory block to allocate and a std::nothrow flag (which is false by default).

Here's an example:

class MyClass {
public:
    void* operator new(size_t size, std::nothrow_t) {
        // Allocate memory using your custom allocator
        return ::operator new(size);
    }
};

In this example, the operator new function allocates memory using the global ::operator new function. You can customize the allocation logic to suit your needs.

Overloading delete

To overload the delete operator, you need to define a function called operator delete in your class. This function should take a single argument: the memory address to deallocate.

Here's an example:

class MyClass {
public:
    void operator delete(void* ptr) {
        // Deallocate memory using your custom deallocator
        ::operator delete(ptr);
    }
};

In this example, the operator delete function deallocates memory using the global ::operator delete function. You can customize the deallocation logic to suit your needs.

Best practices

When overloading new and delete, keep the following best practices in mind:

  1. Use the same allocation and deallocation logic: Ensure that your custom operator new and operator delete functions use the same logic to allocate and deallocate memory.
  2. Avoid throwing exceptions: If your custom operator new or operator delete functions throw exceptions, it can lead to unexpected behavior. Instead, use error codes or return values to indicate allocation or deallocation failures.
  3. Use the std::nothrow flag: When overloading new, use the std::nothrow flag to indicate that the allocation should not throw an exception if it fails.
  4. Test your custom operators: Thoroughly test your custom operator new and operator delete functions to ensure they work correctly and don't leak memory.

Example usage

Here's an example of using a custom operator new and operator delete:

class MyClass {
public:
    void* operator new(size_t size, std::nothrow_t) {
        return ::operator new(size);
    }
    void operator delete(void* ptr) {
        ::operator delete(ptr);
    }
};

int main() {
    MyClass* obj = new MyClass; // Uses custom operator new
    delete obj; // Uses custom operator delete
    return 0;
}

In this example, the MyClass class overloads the new and delete operators to use custom allocation and deallocation logic. The main function demonstrates the usage of the custom operators.