Function argument as a reference to avoid NULL checking

If I have a function that takes a pointer that should never be NULL, I usually do something like this:

void Foo(const somePointer* ptr)
{
  if (ptr == NULL)
  {
    // Throw assertion
    return;
  }

  // Do something
}

So, now I check every time whether the pointer is NULL, and if it is not set to NULL in the first place and is not allocated, then this check is useless. So, now I think whether I should define my functions like this (although I understand that it does not guarantee that I will get a valid object, at least it will not be NULL):

void Foo(const somePointer& ptr)
{
  // No need to check anymore, client is responsible

  // Do something
}

And before I (or I will not, depending on the answers that I get here), I thought that I would ask here and see what everyone had to say, especially its pros and cons.

+3
source share
3 answers

, , , (: , ).
, .

+5

- :

A * a = new A();
f( a );

, f() , :

f( *a );

NULL, , , , , , UB.

+4

, , . , , .

, , , , :

somePointer *ptr = something();
Foo(ptr);

:

somePointer *ptr = something();
Foo(*ptr);

, ptr , , null , " NULL". , .

, , , *, : ", , ". , , - , null - (, strlen), , , . , , , -, , , . .

+4

All Articles