c++thisassert

Do compilers assume that "this" is not nullptr in debug mode?


I wonder if placing assert( this != nullptr ); on every member function is a good idea. I believe that the compiler can just decide to ignore this assert entirely, as it is assumed that this cannot be null, so the assert is always true and can be resolved at compile-time.

But if the compiler does not make this assumption, then this assert is pretty useful to catch problems early.

Do compilers assume this?


Solution

  • No, compilers don't typically assume that. There's even commercial code going around with these checks, some not just asserts but actually logic in them. if (!this) { doSomeWork(); }.

    Although you couldn't reach a situation where this would be NULL without running into undefined behavior, if you're well aware of the implementation details then that's a check you can make; and yes, you're right, it can help in debugging.

    I wouldn't put it everywhere though. Anywhere, for that matter. If this is indeed NULL, you'll likely get a crash later on when you're accessing some member. If you're not accessing any members, consider marking the method static. It also bloats the code unnecessarily.