int main()
{
void* Foo = new???
delete Foo;
}
How do you do something like the above? You can't put new void[size]
. And I don't want to know how to do it with malloc()
and free()
. I already know that works. I'm curious and want to know how it's done with new and delete.
I googled this and saw something about operator new(size)
; and operator delete(size)
;
What is the difference between those and new
/ delete
? Why does C++ not just allow new void* [size]
?
which means it returns a pointer of type (void *), if it returns (void *) I have never seen a code like MyClass *ptr = (MyClass *)new MyClass; I have got confused . void* operator new (std::size_t size) throw (std::bad_alloc); it should return (void *) if I understand the syntax correctly.
Explanation: Because the void pointer is used to cast the variables only, So pointer arithmetic can't be done in a void pointer.
You can not increment a void pointer. Since a void* is typeless, the compiler can not increment it and thus this does not happen.
Since void is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation. Therefore you cannot perform pointer arithmetic on a void pointer.
This will do the trick:
int main()
{
void* Foo = ::operator new(N);
::operator delete(Foo);
}
These operators allocate/deallocate raw memory measured in bytes, just like malloc
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With