What purpose to const besides functional programming?

Simen Kjaeraas simen.kjaras at gmail.com
Thu Jul 24 03:43:04 PDT 2008


Jason House <jason.james.house at gmail.com> wrote:

> Maybe an example will help:
>
> int a;
> int b;
>
> struct bar{
>   void write(int x) invariant
>   out{ assert(a==b); }
>   body{
>     a = x;
>     b = x;
>   }
> }
>
> The state of bar is never modified, but bar should not be used without
> synchronization.  The function's contract can be violated due to a race
> condition.  This may be an artificial example, but I hope it shows that  
> #5
> requires qualification.

You are expecting invariant member functions to not do things they can
and should do. Perhaps this would be better shown with one of the
proposed syntaxes for const/invariant member functions:

struct bar
{
   invariant(this)
   {
     void write(int x) {...}
   }
}

This is essentially what your example above does, and is expected to do.
If it were to behave the way you seem to expect it to, it would look
like this:

struct bar
{
   void write(int x) pure  // int does not need to be marked invariant,
                           // as it is passed by value.
   {
   }
}

This write method would of course be unable to do anything, as it
returns void, and cannot change its parameters.

The fact that invariant member functions require synchronization needs
no debate, we all know that, and most of us expect it to be like that.
The reason is that one might (for any good or bad reason) have an
invariant 'bar' somewhere, and need to call its 'write' method. Seeing
as this does not change the contents of 'bar', it should be a const or
invariant function. If you want it to behave differently for const and
invariant, there needs to be a separate function for the invariant
case.

The invariant object may have been created at run-time, and one might
want to write it to file, and include information about its being
const, mutable or invariant. This would be impossible if any and all
member functions of an invariant object be required to be pure.

Even if the const system was added to D only for functional
programming, we might need to interface to those invariant objects
in some way, and this is where invariant/const member functions
come in.


So, to sum it up:
Invarant/const member functions exist so that one might do things
with invariant/const objects, without using static functions. In
nearly all cases, a const member function is what you want, but
there might be some obscure reason to have an invariant member
function, and I don't think D should deny you that.

-- 
Simen



More information about the Digitalmars-d mailing list