Using new on 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.


void * is convertible to any pointer type. You can simply do void *Foo = new int or any other type that you want. But there really isn't a reason to do this in C++.


C++ travels in constructed objects allocated using some variation of new T. or new T[n] for some type T. If you really need uninitialized memory (it is very rare that you do), you can allocate/deallocate it using operator new() and operator delete():

void* ptr = operator new(size);
operator delete(ptr);

(similarily for the array forms)


Why does C++ not just allow new void[size]?

Because void is not an object; it has no size! How much space should be allocated? Bear in mind that new T[size] is approximately equivalent to malloc(sizeof(T) * size).

If you just want a raw byte array, then you could use char.*


* Although, of course, because this is C++ you should use something like std::vector<char> to avoid memory-leak and exception-safety issues.

Tags:

C++