Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

c++ - Why don't I need to check if references are invalid/null?

Reading http://www.cprogramming.com/tutorial/references.html, it says:

In general, references should always be valid because you must always initialize a reference. This means that barring some bizarre circumstances (see below), you can be certain that using a reference is just like using a plain old non-reference variable. You don't need to check to make sure that a reference isn't pointing to NULL, and you won't get bitten by an uninitialized reference that you forgot to allocate memory for.

My question is how do I know that the object's memory hasn't been freed/deleted AFTER you've initialized the reference.

What it comes down to is that I can't take this advice on faith and I need a better explanation.

Can anyone shed some light?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...