Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if (!this) { return false; }

Tags:

c++

null

this

I stumbled upon this piece of code which seems totaly broken to me, but it does happen that this is null. I just don't get how this can be null

it is inside a normal method call such as

myObject->func();

inside MyObject::func() we have

if (!this) { return false; }

is there any way I can have the first line to throw a NullPointerException instead of going inside the null(?) method?

like image 971
Eric Avatar asked Mar 19 '09 17:03

Eric


2 Answers

If you have:

MyObject *o = NULL;

o->func();

What happens next depends on whether func is virtual. If it is, then it will crash, because it needs an object to get the vtable from. But if it's not virtual the call proceeds with the this pointer set to NULL.

I believe the standard says this is "undefined behaviour", so anything could happen, but typical compilers just generate the code to not check whether the pointer is NULL. Some well known libraries rely on the behaviour I described: MFC has a function called something like SafeGetHandle that can be called on a null pointer, and returns NULL in that case.

You might want to write a reusable helper function:

void CheckNotNull(void *p)
{
    if (p == NULL)
        throw NullPointerException();
}

You can then use that at the start of a function to check all its arguments, including this:

CheckNotNull(this);
like image 200
Daniel Earwicker Avatar answered Sep 24 '22 18:09

Daniel Earwicker


A way to trap these kind of errors (by design) is using a pointer-wrapper class (resembling a shared_ptr) that throws upon creation with a null pointer argument. It may throw also when dereferenced, but that's a little late - better than nothing, I guess.

like image 29
xtofl Avatar answered Sep 20 '22 18:09

xtofl