Others (AshleysBrain and Neil Butterworth), already answered correctly, but I will summarize it here:
- Use references as much as possible
- If using pointers, initialize them either to NULL or to a valid memory address/object
- If using pointers, always verify if they are NULL before using them
- Use references (again)... This is C++, not C.
Still, there is one corner case where a reference can be invalid/NULL :
void foo(T & t)
{
t.blah() ;
}
void bar()
{
T * t = NULL ;
foo(*t) ;
}
The compiler will probably compile this, and then, at execution, the code will crash at the t.blah()
line (if T::blah() uses this
one way or another).
Still, this is cheating/sabotage : The writer of the bar()
function dereferenced t
without verifying t
was NOT null. So, even if the crash happens in foo()
, the error is in the code of bar()
, and the writer of bar()
is responsible.
So, yes, use references as much as possible, know this corner case, and don't bother to protect against sabotaged references...
And if you really need to use a pointer in C++, unless you are 100% sure the pointer is not NULL (some functions guarantee that kind of thing), then always test the pointer.