Today I was writing a little Memory Profiler for my code and for the first time overloaded operator new. In doing so, I figured the syntax is void* operator new(size_t sz). This is indeed very similar to malloc where you have void* malloc(size_t sz).
This got me into thinking since when you use malloc, you need to explicitly cast the pointer back to your data type whereas for new you don’t need to do this. How does the compiler figure out the correct data type for new and why do you have to make it return void *? Isn’t T* operator new(size_t sz) more intuitive?
C++ separates memory allocation and object construction. The allocation function (i.e.
operator new()) returns avoid *to some memory, and thenewoperator constructs an object in that memory. If you will, thenewoperator “converts” memory into an object, and a placement-newexpression is a bit like a “cast”:The default, non-placement form of
newperforms allocation and construction in one go. It’s morally equivalent to the first half of this example. But still, allocation and construction remain two distinct concepts.