It's undefined behavior. The pointer must come from new
or must be a null pointer.
Standard (N3797) 5.3.5[expr.delete]
/2
If the operand has a class type, the operand is converted to a pointer
type by calling the above-mentioned conversion function, and the
converted operand is used in place of the original operand for the
remainder of this section. In the first alternative (delete object),
the value of the operand of delete may be a null pointer value, a
pointer to a non-array object created by a previous new-expression, or
a pointer to a subobject (1.8) representing a base class of such an
object (Clause 10). If not, the behavior is undefined.
[...]
The part left out at the bottom is the same for delete []
.
Deleting is only valid for
- null pointers
- pointers you got from new
- or a base class pointer pointing to the above.
Null pointers:
To follow up on null pointers, calling delete
on a null pointer is a noop and the pointer is still a null pointer afterwards (no need to reassign nullptr
to it). This is guaranteed at least for the standard delete
and deallocation functions. If you define custom ones you should also handle this properly.
Standard 5.3.5 [expr.delete]
/7
If the value of the operand of the delete-expression is not a null pointer value, then:
Otherwise, it is unspecified whether the deallocation function will be called. [ Note: The deallocation function is called regardless of whether the destructor for the object or some element of the array throws an
exception. — end note ]
So delete
might do nothing at all or might call the deallocation function with the null pointer. Lets look at that function next:
Standard 3.7.4.2 [basic.stc.dynamic.deallocation]
/3
If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.
[...]
It is explicitly mentioned that it got no effect.
Note: If you define your own custom deallocation functions you should make sure you handle it the same way. Not handling null pointers properly would be evil.