Why is the new operator allowed to return *void to every pointer-type?

You have confused the new operator and the operator new function. No problem, everybody does. They are almost the same, except that they are different.

The function void* operator new(size_t) grabs a block of raw, untyped memory from whatever tree it grows on, and returns it to the program.

void* raw_memory = ::operator new(42);

It is an ordinary function with somewhat weird name.

The new operator is not a function and not a function call. It’s a separate language construct. It takes raw memory (normally, one returned by the void* operator new(size_t) function) and turns it into an object by calling a constructor. It then returns a properly typed pointer to the newly-created object.

Fish* f = new Fish;

UPDATE Naturally, there is also the delete operator (the opposite of the new operator) and the void operator delete(void*) function (the opposite of the void* operator new(size_t) function).

There are also the new[] operator, the delete[] operator, the void* operator new[](size_t) function, and the void operator delete[](void*) function; they deal with arrays of objects (as opposed to individual objects).

There are also so-called “placement new” forms that do not call any of the operator new functions for fresh memory, but instead require an explicit pointer to raw memory. They have no corresponding built-in “delete” forms. You can roll your own if you are so inclined, but I refuse to talk about any of this while being sober.

Leave a Comment