← Back to team overview

dolfin team mailing list archive

Re: const in la classes

 

On Thu, Mar 15, 2007 at 10:30:30PM +0100, Garth N. Wells wrote:
> 
> 
> Anders Logg wrote:
> > On Thu, Mar 15, 2007 at 10:12:09PM +0100, Garth N. Wells wrote:
> > 
> >> What's the problem with const? Not much might happen in these functions, 
> >> but M and N are not meant to be changed by the init function, so we 
> >> might as well use const.
> >>
> >> Garth
> > 
> > Yes, but one could say this is the business of the body/implementation
> > of the function. M and N (or other const variables) are passed by
> > value so to the caller they will always remain constant. The function
> > does not need to announce to the outside world what it does
> > internally.
> > 
> 
> True, but I see const and protecting the init function from itself (or 
> more accurately, the person writing init()). If const can be used, why 
> not use it?

I think it clutters the interface. We should reserve the use of const
for when it actually means something (to the caller).

When an argument is passed-by-value, then const has no meaning (except
inside the body of the function). So my suggestion would be the
following:

1. Don't use const in headers when it has no meaning there.

2. Use const in the implementation.

The following code is valid (and it is valid because const on
variables passed-by-value has no meaning):

// No const in declaration
void foo(int a);

// But const in definition
void foo(const int a)
{
   ...
}

Also note that you can equally well put const in the declaration but
not in the definition, so the const in the declaration does not force
the person implementing the function to put in const anyway.

/Anders




> > If we have
> > 
> >     bar(const Foo& foo);
> > 
> > then the const means something (we could change the value of foo
> > inside the function were it not for the const), but to the outside
> > world, there is no difference between these two:
> > 
> >     bar(foo)
> >     bar(const foo);
> > 
> > If we want to have the const on everything passed by value, then we
> > should also have
> > 
> >     const int* const rows
> > 
> > as well in the argument list, but
> > 
> >     const int* rows
> > 
> > should be enough (we promise not to change the values in the array
> > rows), but we might (internally in the body of the function) change the
> > value of the local copy of the pointer (the pointer is passed by
> > value).
> >
> 
> But is this a reason for not using const in init()?
> 
> Garth
> 
> > /Anders
> > 
> 
> 
> _______________________________________________
> DOLFIN-dev mailing list
> DOLFIN-dev@xxxxxxxxxx
> http://www.fenics.org/mailman/listinfo/dolfin-dev


References