You can't know if references are invalid:
There is no way to know if your reference is referencing valid memory except by taking care of how you use references. For example you don't want to use a reference with something created on the heap if you are unsure when the memory will be deleted.
You also can never know whether the pointer you are using is pointing to valid memory or not as well.
You can do NULL checks with both pointers and references but typically you would never do a NULL check with a reference because no one would ever write code like this:
int *p = 0;
int &r = *p;//no one does this
if(&r != 0)//and so no one does this kind of check
{
}
When to use a reference?
You probably want to use references in cases like this:
//I want the function fn to not make a copy of cat and to use
// the same memory of the object that was passed in
void fn(Cat &cat)
{
//Do something with cat
}
//...main...
Cat c;
fn(c);
Shooting yourself in the foot is hard with references:
It's much harder to shoot yourself in the foot with references than it is with pointers.
For example:
int *p;
if(true)
{
int x;
p = &x;
}
*p = 3;//runtime error
You can't do this sort of thing with references since a reference must be initialized with it's value. And you can only initialize it with values that are in your scope.
You can still shoot yourself in the foot with references, but you have to REALLY try to do it.
For example:
int *p = new int;
*p = 3;
int &r = *p;
delete p;
r = 3;//runtime error
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…