Search code examples
c++functionnew-operatordelete-operator

Why does c++ have its separate syntax for new & delete?


Why can't it just be regular function calls? New is essentially:

malloc(sizeof(Foo));
Foo::Foo();

While delete is

Foo:~Foo();
free(...);

So why does new/delete end up having it's own syntax rather than being regular functions?


Solution

  • Here's a stab at it:

    The new operator calls the operator new() function. Similarly, the delete operator calls the operator delete() function (and similarly for the array versions).

    So why is this? Because the user is allowed to override operator new() but not the new operator (which is a keyword). You override operator new() (and delete) to define your own allocator, however, you are not responsible (or allowed to for that matter) for calling appropriate constructors and destructors. These function are called automatically by the compiler when it sees the new keyword.

    Without this dichotomy, a user could override the operator new() function, but the compiler would still have to treat this as a special function and call the appropriate constructor(s) for the object(s) being created.