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?
If you have:
What happens next depends on whether
funcis 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
SafeGetHandlethat can be called on a null pointer, and returns NULL in that case.You might want to write a reusable helper function:
You can then use that at the start of a function to check all its arguments, including
this: