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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With