Why would deleting an object through void*
be undefined behavior, rather than compilation error?
void foo(void* p) {
delete p;
}
This code compiles and produces code, albeit with the warning on gcc and clang (surprisingly, ICC doesn't give a warning):
:2:5: warning: cannot delete expression with pointer-to-'void' type 'void *' [-Wdelete-incomplete]
Why is not simply malformed program with invalid syntax? Looks like Standard doesn't spend too much time on it, saying in [expr.delete]
that
This implies that an object cannot be deleted using a pointer of type void* because void is not an object type.
Would there be any reason I am missing why this does not trigger a hard compilation error?
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.
When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.
In modern C++ deleting a void *
pointer is ill-formed (i.e. it is what we typically call a "compilation error")
8.3.5 Delete
1 [...] The operand shall be of pointer to object type or of class type.
void *
is not a pointer to object type.
In C++98 the situation was different. Deleting a null pointer of void *
type was a NOP, while deleting a non-null pointer of void *
type was UB.
This change in the specification appears to have been triggered by defect report #599. The original spec allowed supplying null pointers of any pointer type in delete-expression, like function pointers, for example. This looked unnecessarily permissive. The resolution of DR#599 tightened the requirements, outlawing void *
as well.
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