Say I have the following function:
void destroy(Song* song) {
if (song)
delete song;
}
Can the implementation be changed to the following, to remove the null validation?
void destroy(Song*& song) {
delete song;
}
If yes, why?
Say I have the following function:
void destroy(Song* song) {
if (song)
delete song;
}
Can the implementation be changed to the following, to remove the null validation?
void destroy(Song*& song) {
delete song;
}
If yes, why?
You don't need to check for null, delete
on a null pointer is valid and does nothing.
See Is it safe to delete a NULL pointer?
If we assume delete
on a null pointer would not be valid, then your second implementation of destroy
wouldn't work, because the user can still do the following:
Song* p = nullptr;
destroy(p);
From the C++ Standard (8.3.5 Delete)
- ...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 (4.5) representing a base class of such an object (Clause 13). If not, the behavior is undefined. In the second alternative (delete array), the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression.83
Sp the check for a null-pointer is redundant. The same is valid for the C function free
.