0

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?

O.B.
  • 29
  • 1
  • 7
  • 1
    Using a pointer or a reference to a pointer makes no difference here. – super Dec 30 '19 at 12:03
  • @super - it does, a reference to pointer (2nd version) would not work if the original pointer is NULL – artm Dec 30 '19 at 12:06
  • 1
    @artm It's perfectly fine and legal to make a reference to a `NULL`-pointer. A reference does not care about the value of the referenced object. – super Dec 30 '19 at 12:08
  • @artm Why wouldn't it? Look at emlai's answer. – Ted Lyngmo Dec 30 '19 at 12:09
  • @super ah, so you can't have a reference to NULL, but you can have a reference to a pointer to NULL. – artm Dec 30 '19 at 12:21
  • @artm Not pointer-to-`NULL`, `NULL` represents a *null pointer value*. It is a *value* of a pointer variable, not something that it points to. You can form a rvalue reference to or `const` lvalue reference to `NULL`, just not a non-`const` lvalue reference, because `NULL` is a prvalue. – walnut Dec 30 '19 at 12:23
  • @artm You can have a `const reference` to a value. Since `NULL` is a value, you can actually have a reference to `NULL`. A reference must however refer to *something*, so in some sense you are right even if the wording is not. – super Dec 30 '19 at 12:28

2 Answers2

5

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);
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
2

From the C++ Standard (8.3.5 Delete)

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335