Re: Terminology problem
From: Arthur J. O'Dwyer (ajo_at_nospam.andrew.cmu.edu)
Date: 06/07/04
- Next message: Arthur J. O'Dwyer: "Re: c-libs namespace"
- Previous message: Jeff Schwab: "Re: VS2002 . NET"
- In reply to: David White: "Re: Terminology problem"
- Next in thread: Gary Labowitz: "Re: Terminology problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 7 Jun 2004 09:27:42 -0400 (EDT)
On Mon, 7 Jun 2004, David White wrote:
>
> "Gary Labowitz" <glabowitz@comcast.net> wrote...
> >
> > int &rVal = val;
> > decalres a new name for the variable val. It is rVal.
> > You may now use rVal and val interchangeably.
> > rVal is called a reference to val. It exists as long as val exists;
> > that is, they share the same scope.
>
> They don't necessarily share the same scope. A reference can be born after,
> and die before, the object to which it refers, or it can refer to an object
> that no longer exists. Obviously, you can't allow the latter case to ever
> happen.
Right. As Francis says, the correct term for "exists as long as
val exists" is *lifetime*. rVal and val, being the same object, have
the same lifetime. rVal and val, being different names, may or may
not have different scope.
Examples, just for fun:
void foo(const int &v) { int &rVal = v; }
int main() { int val; foo(val); return 0; }
Here, the scopes of 'rVal' and 'val' do not overlap at all (when
the name 'rVal' is in scope, 'val' is out of scope, and vice versa).
Yet all three names --- 'val', 'v', and 'rVal' --- refer to the
same object.
int main() {
int *p = new int(42);
int &rVal = *p;
delete p;
rVal;
return 0;
}
Here, the scopes of 'p' and 'rVal' are almost the same ('rVal' is
created just a little later). But the lifetime of the object pointed
to by 'p' is shorter than the "lifetime" of 'rVal', because it gets
explicitly destroyed while the name 'rVal' is still in scope. I
don't think that immediately causes undefined behavior, but the
next line --- the one that evaluates the "value" of the no-longer-extant
'rVal' --- is definitely incorrect, and will cause undefined behavior.
In fact, since a reference is just another name for an existing object,
once *p has been destroyed, there is no way to "re-attach" 'rVal' to
another object. The reference is just dead at this point, and can no
longer be used for anything (except as an argument to 'sizeof').
-Arthur
- Next message: Arthur J. O'Dwyer: "Re: c-libs namespace"
- Previous message: Jeff Schwab: "Re: VS2002 . NET"
- In reply to: David White: "Re: Terminology problem"
- Next in thread: Gary Labowitz: "Re: Terminology problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|