I was looking at the signature of new operator. Which is:
void* operator new (std::size_t size) throw (std::bad_alloc);
But when we use this operator, we never use a cast. i.e
int *arr = new int;
So, how does C++ convert a pointer of type void*
to int*
in this case. Because, even malloc
returns a void*
and we need to explicitly use a cast.
There is a very subtle difference in C++ between
operator new
and thenew
operator. (Read that over again... the ordering is important!)The function
operator new
is the C++ analog of C'smalloc
function. It's a raw memory allocator whose responsibility is solely to produce a block of memory on which to construct objects. It doesn't invoke any constructors, because that's not its job. Usually, you will not seeoperator new
used directly in C++ code; it looks a bit weird. For example:The
new
operator is a keyword that is responsible for allocating memory for an object and invoking its constructor. This is what's encountered most commonly in C++ code. When you writeYou are using the new operator to allocate a new integer. Internally, the
new
operator works roughly like this:operator new
.operator delete
, then propagate the exception.Because the
new
operator andoperator new
are separate, it's possible to use thenew
keyword to construct objects without actually allocating any memory. For example, the famous placement new allows you to build an object at an arbitrary memory address in user-provided memory. For example:Overloading the
new
operator by defining a customoperator new
function lets you usenew
in this way; you specify how the allocation occurs, and the C++ compiler will wire it into thenew
operator.In case you're curious, the
delete
keyword works in a same way. There's a deallocation function calledoperator delete
responsible for disposing of memory, and also adelete
operator responsible for invoking object destructors and freeing memory. However,operator new
andoperator delete
can be used outside of these contexts in place of C'smalloc
andfree
, for example.You confuse
new
expression withoperator new()
function. When the former is compiled the compiler among other stuff generates a call tooperator new()
function and passes size enough to hold the type mentioned in thenew
expression and then a pointer of that type is returned.