I saw this code snippet during our lab and it actually compiles in MSVC2008 and G++.
void LinkList< class T >::Insert(T n)
{
if (this == NULL)
// some code here
}
As far as I know the this must not be null since you cannot call a class functions in c++ if it wasn’t instantiated. Is this a valid code? if so what’s the reason behind and where it can be useful?
The thing is, you can, but it leads to undefined behavior.
Such a check should probably be an assert, though such code isn’t guaranteed to actually work by the standard. (If
thisis null, you’re already in undefined behavior land.)The reason it’s “useful” is to detect using an object after it’s been deleted, or if it was never created:
Within
foo, you could assert, “hey, we messed up :/”.In my opinion such use is indicative of bad design. You shouldn’t have a pointer lying around that might possibly get invoked again. The last thing you do with a pointer is
deleteit; if it’s still around after that, change your code so it’s not.