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);