[LC++]can't seem to use reference
Carlo Wood
carlo at alinoe.com
Mon Feb 18 13:00:57 UTC 2002
On Mon, Feb 18, 2002 at 11:03:06AM +1030, Mark Phillips wrote:
> Carlo Wood wrote:
> >
> > On Tue, Feb 12, 2002 at 01:27:31PM +1030, Mark Phillips wrote:
> > > 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
> > > // ...
> > > }
> >
> > int next=0;
> > for (int i=0; i<N; ++i) {
> > largeStructTy const& ls=largeStructList[next];
> > largeStructTy const& nextLs=largeStructList[(next=i+1)];
> > // do stuff involving the reading of ls and nextLs
> > // ...
> > }
>
> Thanks for this solution. My only concern with it is the
> possibility of inefficiency. My solution (if it were legal C++)
> would only require one large structure to be read from memory
> each iteration (the rest is simply pointer swapping). Your
> solution requires two large structures to be read each iteration.
> Or would the compiler optimize this away?
My 'solution' doesn't copy anything at all, there are only
reference initializations.
TYPE& foo = initializer;
is equivalent with
TYPE& foo(initializer);
and functionally equivalent with
TYPE* const foo_ptr = &initializer;
// use (*foo_ptr)
Actually, I hadn't noticed that you copied data from 'i+1' to 'i';
So I should have typed:
for (int i = 0; i < N; ++i)
{
largeStructTy const& ls(largeStructList[i]);
largeStructTy const& nextLs(largeStructList[i]);
nextLs = largeStructList[i + 1];
// do stuff involving the reading of ls and nextLs
// ...
}
which is equivalent with your pseudo code.
Note that there is no difference at all between ls and nextLs.
I can assume that what you really want is this:
Copy element i+1 to i, keep a reference to both, where
reference ls corresponds to i and nextLs to i+1.
That would be:
for (int i = 0; i < N; ++i)
{
largeStructTy const& ls(largeStructList[i]);
largeStructTy const& nextLs(largeStructList[i+1]);
ls = nextLs;
// do stuff involving the reading of ls and nextLs
// ...
}
> Ie, why the use of "next"?
I applied a 'code transformation' from "lsNext as variable" to
"lsNext as reference with variable index 'next'". Since 'next'
and 'i' are related, you can eliminate 'next' again ofcourse.
I thought that not 'optimizing' the code would make it more
clear what I had done.
--
Carlo Wood <carlo at alinoe.com>
More information about the tuxCPProgramming
mailing list