Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using new on void pointer

Tags:

c++

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]?

like image 285
Brandon Avatar asked Jan 01 '13 16:01

Brandon


People also ask

Does New return a void pointer?

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.

What can't you do on a void pointer?

Explanation: Because the void pointer is used to cast the variables only, So pointer arithmetic can't be done in a void pointer.

Can you add to 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.

What happens if we do addition on a void pointer?

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.


1 Answers

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.

like image 134
Yakov Galka Avatar answered Nov 05 '22 08:11

Yakov Galka