Search code examples
c++operator-overloadingnew-operator

Overloading new operator: How the size will be passed?


I have one doubt with this code:

#include <iostream>
#include <stdlib.h>

using namespace std;
void * operator new(size_t size)
{
    cout << "New operator overloading " <<"\n";
    void * p = malloc(size);
    return p;
}

void operator delete(void * p)
{
    cout << "Delete operator overloading " <<"\n";
    free(p);
}

int main()
{
    int n = 3, i;
    int * p = new int[3];

    for (i = 0; i<n; i++)
    p[i]= i;

    cout << "Array: ";
    for(i = 0; i<n; i++)
    cout << p[i] << " ";

    cout << endl;

    delete p;
}

How will the size of int[3] be passed as the parameter to void * operator new(size_t size)?

See the following code, this will not work:

#include <iostream>

using namespace std;

void sizef(size_t n)
{
    cout<<n;
}

int main()
{
    sizef(int[5]);
}

Please explain how this works.


Solution

  • The standard [expr.new] reads:

    A new-expression may obtain storage for the object by calling an allocation function. ... If the allocated type is an array type, the allocation function's name is operator new[] and the deallocation function's name is operator delete[]. ... A C++ program can provide alternative definitions of these functions and/or class-specific versions.

    and 1:

    new T[5] results in one of the following calls:

    • operator new[](sizeof(T) * 5 + x)
    • operator new[](sizeof(T) * 5 + x, std::align_val_t(alignof(T)))

    Here, each instance of x is a non-negative unspecified value representing array allocation overhead; the result of the new-expression will be offset by this amount from the value returned by operator new[]. ... The amount of overhead may vary from one invocation of new to another.


    1 Note that operator new[] allocates the storage, it does not construct objects. Object construction and initialization is another part of the job performed by new.