In C++ it is not allowed to assign an void* pointer to any integral pointer without an explicit cast. This requires the use of an static_cast.
But what is with this:
int* iptr = new int;
I know that new operator is defined as following:
void* operator new(size_t);
How does C++ handle this?
I know that this is a basic question, but important. I also know that low-level code must use void. But how can this assignment be legal? iptr is a pointer to an int and new returns a pointer to void, which should trigger a message like “error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]”.
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.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.UPDATE Naturally, there is also the delete operator (the opposite of the new operator) and the
void operator delete(void*)function (the opposite of thevoid* operator new(size_t)function).There are also the new[] operator, the delete[] operator, the
void* operator new[](size_t)function, and thevoid 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 newfunctions 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.