suppose the code does the following:
T *pointer = new T();
delete static_cast<void*>(pointer);
what is result? Undefined, memory leak, memory is deleted?
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.
static_cast is used to convert from pointer to base class to pointer to derived class, or between native types, such as enum to int or float to int. The user of static_cast must make sure that the conversion is safe. The C-style cast does not perform any check, either at compile or at run time.
In C++ the static_cast<>() will allow the compiler to check whether the pointer and the data are of same type or not. If not it will raise incorrect pointer assignment exception during compilation.
The behavior is undefined. Concerning the delete expression, the C++ standard says:
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined. (§5.3.5/3)
Then the footnote to this paragraph clearly states:
This implies that an object cannot be deleted using a pointer of type
void*
because there are no objects of typevoid
(note 73).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With