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?
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.