new
always invokes a constructor (although in the case of PODs something else happens). Sometimes – very rarely – you want to deal with raw memory, not associated with any type. This can be the case when you’re implementing your own allocator
class. Even then, malloc
is rarely the right thing to do but sometimes you may want to take advantage of realloc
i.e. be able to resize the underlying storage more efficiently. This is one scenario that would require malloc
to get the initial storage.
Another actual use-case for raw memory is when you find yourself implementing a “non-predictable” pseudo-random number generator (don’t!). In order to increase the entropy available to the generator, you might use uninitialized memory as a basis for the random seed. Entropy from various sources in the hardware is crucial for such operations so using uninitialized memory (about which not many predictions can be made) can be desirable, if you know exactly what you’re doing.
For completeness’ sake I should point out that the same can be achieved by calling ::operator new
instead of malloc
. The latter also does some checking to see whether the required amount of memory could be allocated successfully and invokes the appropriate callback handlers if something goes wrong (cf. _set_new_handler
). Last but not least, ::operator new
will throw std::bad_alloc
if no handler manages to free enough memory (unless std::nothrow
was specified as the second argument, in which case 0
will be returned).