Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete void pointer?

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

MyCls* c = new MyCls(); void* p = (void*)c; delete (MyCls*)p; 
like image 562
user3277361 Avatar asked Jul 16 '14 05:07

user3277361


People also ask

Can you delete a void pointer?

It is also called general purpose pointer. It is not safe to delete a void pointer in C/C++ because delete needs to call the destructor of whatever object it's destroying, and it is impossible to do that if it doesn't know the type.

What is a void * pointer in C?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

Can you return a void pointer in C?

The malloc() and calloc() function return the void pointer, so these functions can be used to allocate the memory of any data type.


2 Answers

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.

like image 72
StilesCrisis Avatar answered Sep 28 '22 07:09

StilesCrisis


The code is well-defined. Both casts are static casts, although it is good style to make this explicit (static_cast<void*>, etc.) instead of using C-style casts. The standard says that if a pointer to object is converted to a void pointer and back by static casts, it will keep its original value. Thus, your final delete expression shall have the same effect as delete c.

That being said, use of void* is often a code smell in C++.

like image 35
Brian Bi Avatar answered Sep 28 '22 05:09

Brian Bi