>James A. Crotinger writes:
> > on 3/23/00 1:13 PM, oon-digest at owner-oon-digest@oonumerics.org wrote:
> >
> > > void rank1Update(Matrix& A, const Vector& x)
> > > {
> > > for (int i=0; i < A.rows(); ++i)
> > > for (int j=0; j < A.cols(); ++j)
> > > A(i,j) += x(i) * x(j);
> > > }
> > >
> > > [...] However, the compiler can't be sure that the data in the matrix A
> > > doesn't overlap the data in the vector x -- there is a possibility that
> > > writing to A(i,j) could change the value of x(i) partway through.
> >
> > This one has always bothered me - why isn't "const" enough to tell the
> > compiler that x isn't being changed by the assignment.
Jeremy's example was a good illustration of how const doesn't say
anything about aliasing. Here is an orthogonal reason for why
applying const to Vector does not mean that the elements of the
vector are const.
Why does this program compile without errors?
class Vector {
public:
double* z;
};
void foo(const Vector& x)
{
x.z[3] = 5; // !!
}
Answer: const Vector& acts as if it is:
class Vector {
public:
double const* z; // Cannot change z
};
instead of
class Vector {
public:
const double* z; // Cannot change z[i]
};
When you apply const to a compound type, the members become const (+).
The pointer becomes const, but not the things pointed to by it.
(+) more precisely: the non-static non-mutable non-reference members
become const
On the other hand, if we had defined Vector as:
class Vector {
public:
double z[3];
};
then the elements of a const Vector& WOULD be const.
Moohaha,
Todd
-- Todd Veldhuizen tveldhui@acm.org Indiana Univ. Comp. Sci. http://extreme.indiana.edu/~tveldhui/--------------------- Object Oriented Numerics List -------------------------- * To subscribe/unsubscribe: use the handy web form at http://oonumerics.org/oon/ * If this doesn't work, please send a note to owner-oon-list@oonumerics.org
This archive was generated by hypermail 2b29 : Wed Feb 20 2002 - 03:20:10 EST