Function argument as reference to avoid checking for NULL
If I have a function that takes in a pointer which 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 not allocated either then that check is useless. So now I am thinking whether I should define my functions like so (although I realize that does not guarantee I get a valid object, at least 开发者_高级运维it won't be NULL):
void Foo(const somePointer& ptr)
{
// No need to check anymore, client is responsible
// Do something
}
And before I do (or don't, depending on the answers I get here), I thought I would ask here and see what everyone has to say, especially its pros and cons.
Well, if you never ever want a non-existent object passed in, use a reference (Note: non-existent, not non-valid).
If you want that possibility, use a pointer.
A lot depends on the shape of your code - if you write a lot of stuff like this:
A * a = new A();
f( a );
then it seems sensible for f() to take a pointer, rather than to have to write:
f( *a );
Personally, I almost never check for NULLs, new can't return one, and if you find you have one you are probably already in UB land.
I think it's pointless as a safety check. It's marginally worthwhile as documentation, though.
If you make the change, all that will happen is that some user will change this code:
somePointer *ptr = something();
Foo(ptr);
To this:
somePointer *ptr = something();
Foo(*ptr);
Now, if ptr
was null, then the first code is invalid, and it was their fault for passing null into a function whose parameter "should never be NULL". The second code is also invalid, and it was their fault for dereferencing a null pointer.
It's useful as documentation, in that maybe when they type the *
character they will think, "oh, hang on, this better not be null". Whereas if all you've done is document that null is an invalid input (like, say, strlen
does), then they'd have to read the documentation in order to know not to pass in a null pointer. In theory, the user of your code will check the docs instead of just mashing the keyboard with his face until he has something that compiles, and assuming that will work. In practice, we all have our less intelligent moments.
精彩评论