Yes, the check for non-null is required by the standard (C++11, [unique.ptr.single.modifiers]§4
):
void reset(pointer p = pointer()) noexcept;
4 Effects: assigns
p
to the stored pointer, and then if the old value of the stored pointer,old_p
, was not equal tonullptr
, callsget_deleter()(old_p)
. [ Note: The order of these operations is significant because the call to get_deleter() may destroy*this
. —end note ]
(emphasis mine)
Discussion: An alternative way to standardise it would be to put the "burden" on the user of the class, i.e. require all deleters (the default one and any custom ones) to work fine when invoked on a null pointer.
However, I understand the idea was to enable functions like free()
and even things like a hypothetical unlock_mutex(Mutex*)
to work as deleters out-of-the-box, regardless of how/if they handle null pointers. So putting this check into the unique_ptr
itself broadens the selection of deleters which can be used directly.