Search code examples
c++new-operatordynamic-memory-allocation

Who defines the new operator?


Is this program supposed to compile?

int main(){
    double* p = new double[4];
    delete[] p;
    return 0;
}

(It does compile with GCC 7.1.1)

The reason I ask this is because, I am not sure who is providing the definition of the operator new. Is it the language? is the compiler by default #includeing <new>?

To make this question more clear I can actually define (overwrite?) operator new.

#include<cstdlib> // malloc and size_t
#include<cassert> // assert
void* operator new[](unsigned long int sz){ // what if this is not defined? who provides `new`?
    assert(0); // just to check I am calling this function
    return std::malloc(sz);
}
int main(){
    double* p = new double[4]; // calls the new function above
    delete[] p;
    return 0;
}

What am I doing here?

overriding new? overloading new? Is the definition of new special (magic) for the compiler? (e.g. if not defined use a language provided one). What is the role of #include<new> in all this?


Solution

  • Here you have a new expression, which invokes indeed operator new[]

    void* operator new[]( std::size_t count );
    

    The compiler is implicitly declaring the basic operator news in each translation unit (this is specified by the standard), see the cppreference documentation.

    The versions (1-4) are implicitly declared in each translation unit even if the < new> header is not included.

    In your second code snippet, you are overloading (technically you are actually replacing) operator new (not overriding, that's only for virtual functions), although you should overload operator new[] instead (note that if you don't, then operator new[] will fall back on operator new, so technically I believe your code is OK, but I'd just overload the array version for clarity).