How to delete void pointer?

user3277361 picture user3277361 · Jul 16, 2014 · Viewed 15.5k times · Source

Is there anything wrong when deleting an object like this in C++?

MyCls* c = new MyCls();
void* p = (void*)c;
delete (MyCls*)p;

Answer

StilesCrisis picture StilesCrisis · Jul 16, 2014

This as written is legal.

The cast back to MyCls* is critical. Without that, you will invoke undefined behavior--the MyCls destructor will not be called, and other problems may arise as well (such as a crash). You must cast back to the correct type.

Also note that this can be complicated if multiple inheritance is involved and multiple casts are used. Your casts must "match" in either direction.

If your code is structured such that you won't know the type at the time of destruction, give each deletable object a common base class with a virtual destructor. Then cast back to the base class before delete is called.