Does it ever make sense to check if "this" is null?

c++, null, pointers

Solution

Does it ever make sense to check for this==null? I found this while doing a code review.

In standard C++, it does not, because any call on a null pointer is already undefined behavior, so any code relying on such checks is non-standard (there's no guarantee that the check will even be executed).

Note that this holds true for non-virtual functions as well.

Some implementations permit `this==0`, however, and consequently libraries written specifically for those implementations will sometimes use it as a hack. A good example of such a pair is VC++ and MFC - I don't recall the exact code, but I distinctly remember seeing `if (this == NULL)` checks in MFC source code somewhere.

It may also be there as a debugging aid, because at some point in the past this code was hit with `this==0` because of a mistake in the caller, so a check was inserted to catch future instances of that. An assert would make more sense for such things, though.

If this == null then that means the object is deleted.

No, it doesn't mean that. It means that a method was called on a null pointer, or on a reference obtained from a null pointer (though obtaining such a reference is already U.B.). This has nothing to do with `delete`, and does not require any objects of this type to have ever existed.

Problem

Say I have a class with a member function; inside that method, I check `this == nullptr`, and if it is, return an error code. If `this` is null, then that means the object is deleted. Is the method even able to return anything? Update: I forgot to mention that the method can be called from multiple threads and it may cause the object to be deleted while another thread is inside the member function.

Original source