[LC++]can't seem to use reference

Mark Phillips mark at austrics.com.au
Mon Feb 18 03:52:03 UTC 2002


Hi All,

Suppose I've got an array of large structures, and I want to read
parts of these structures without making local copies.  One way
would be to use a few "largeStructTy const* lsPr", ie use some
pointers to constant largeStructTy.  This will work, but is a bit
messy, having to dereference the pointer every time I wish to look
at something.  A nicer thing to use is things like
"largeStructTy const& ls".  It's basically the same thing, but I can
treat it as an actual (read only) largeStructTy object.  This works
well if I do something like:

for (int i=0; i<N; ++i) {
  largeStructTy const& ls=largeStructList[i];
  // do stuff involving the reading of ls
  // ...
}

But supposing I want the lifetime of one of these "ls" variables 
to be longer than one iteration of the loop?  Eg, consider:

largeStructTy const& nextLs=largeStructList[0];
for (int i=0; i<N; ++i) {
  largeStructTy const& ls=nextLs;
  nextLs=largeStructList[i+1];
  // do stuff involving the reading of ls and nextLs
  // ...
}

The compiler won't allow me.  It says I am not allowed to do the
assignment of nextLs.  If I turned this assignment into a construction,
the compiler wouldn't make this complaint.  But the value of nextLs 
would not persist between iterations of the loop.

I can get around this problem by using pointers instead of references,
but I really don't want to if I don't have to.  Is there a way around
the problem other than using pointers?  Is this a deficiency with
C++?

Cheers,

Mark.



More information about the tuxCPProgramming mailing list