This code will work the way it is, but if you do this, you pretty much need to write a matching ::operator delete
that will work with it:
void operator delete(void *block) throw() {
::free(block);
}
Personally, I'd probably modify your code to something more like:
void *operator new(size_t size) throw(std::bad_alloc)
{
void *p = malloc(size);
if(!p)
throw bad_alloc();
return p;
}
I prefer to initialize everything I can, rather than create an uninitialized variable, and only later assign a value to it. In this case, the difference is pretty minor, but I consider it a habit worth cultivating.
As far as being more effective than the default implementation of operator new
, I'd say chances are that no, it won't be more effective, and might well be less effective. What you've provided is basically how many standard libraries were implemented toward the dawn of C++, but since then, many (most?) have done more work on their implementation of ::operator new
to tailor it more closely to how dynamically allocated memory tends to be used in C++ (where malloc
is mostly oriented toward how it's used in C, which is typically at least a little different).
As far as new[]
goes, yes, it's just a change of function signature. Despite being used for single vs. multiple allocations, the requirements on operator new
and operator new[]` are identical.