Tuesday, 4 September, 2007

Global vs Member overloaded operator new

In an earlier post we saw how to overload operator new, which will allow us to have customized memory allocation for an object on heap.

Its possible to place this overloaded operator new function either globally or as member function within a class.

 

// Global overloaded operator new
void *operator new(size_t size)
{
    return malloc(size);
}

 

// Class CTest
class CTest
{
public:

    // Member overloaded operator new
    void *operator new(size_t size)
    {
        return malloc(size);
    }

};

 

Is there any behavioral difference between these two versions of operator new?

Yes, there is.

If we have overloaded new as a member function within a class, it will always have high precedence over the globally defined version.

If we have a globally defined operator new function, the same will be used for all classes which doesn't have overloaded operator new defined within.

If both exist, the member version will be preferred over the global version.

Is there any advantage of this feature?

Yes.

Global version of overloaded operator new will be very much useful when we need to have a common strategy for memory allocation for all the classes in the module.

If we are in a situation where we need to have a specific way for allocation for a particular class which is different from others then we can overload operator new for the class with desired allocation method. A good example would be to allocate and initialize the allocated memory with zeros.