Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does deleting void pointer guarantee to delete right size? [duplicate]

Possible Duplicate:
Is it safe to delete a void pointer?

Say I have a new allocation to a class called MyClass and allocation is as simple as:

MyClass *myClassPtr = new MyClass();

And I store reference to the list of void* where I simply say

myListOfPointers.add(static_cast<void*>(myClassPtr)); // this has to be void*

And later I release memory so instead of doing:

delete myClassPtr

I use:

delete MyListOfPointer.get(0)

(Say myClassPtr reference is at zero-index.) Also, please note that it has to be void* since this list can store different types of pointers so I wouldn't know the type of pointer that I am deleting:

So I can't do any thing like:

delete static_cast<MyClass*>(MyListOfPointer.get(0))

Is this way going to release the correct memory size? (sizeof(MyClass))?

Note:
I am not looking for any answer pointing to smart pointers.

like image 875
abumusamq Avatar asked Oct 06 '12 17:10

abumusamq


1 Answers

Deleting through a void* results in undefined behavior, so you are guaranteed nothing.

5.3.5 Delete [expr.delete]

1 The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.
[...]
The operand shall have a pointer to object type, or a class type having a single non-explicit conversion function (12.3.2) to a pointer to object type. The result has type void.78

78) This implies that an object cannot be deleted using a pointer of type void* because void is not an object type.

Emphasis mine.


So even though you said not to say it, the answer is to create some form of smart pointer. It would need to use type-erasure to hide the type externally (allowing the heterogeneous list), but internally keep track of the type it was given and how to delete it. Something much like boost::any.

like image 172
GManNickG Avatar answered Oct 09 '22 13:10

GManNickG