In addition to checking for 0
(NULL
), one solution would be to refactor your code so you force the pointer to always be valid. This is not always possible, but in most cases, it's the best solution.
In your case (as in most other cases), this means initializing the pointer in the constructor (i.e. as soon as its lifetime starts) and destroy it at the end of its lifetime. Make the variable private
and don't allow direct write access to it to ensure that it will always stay valid.
This is an often used pattern in C++ and it effectively bounds the object lifetime of the pointee to the lifetime of your class. Sometimes, it might also be a viable solution to provide some kind of reset
that deletes the pointer and immediately re-initializes it. If this is written in an exception-safe way, you've also ensured that your pointer will never be invalid.
Do not create a bool
ean flag to keep track of your pointer's validity. This solution has no advantage, and many disadvantages, to setting the pointer to 0
.