Fully transitive const is not necessary

Steven Schveighoffer schveiguy at yahoo.com
Fri Apr 4 10:22:36 PDT 2008


"Leandro Lucarella" wrote
> Steven Schveighoffer, el  4 de abril a las 09:24 me escribiste:
>> class C
>> {
>>    // this is like a struct passed as an argument to all methods, and is
>> always mutable
>>    nonstate
>>    {
>>        int c;
>>    }
>>
>>    // is passed an implicit nonstate pointer to the nonstate values
>>    int f(int x) const
>>    {
>>        return nonstate.c++;
>>    }
>> }
>
> Why don't you just do something like this:
>
> static int[C] nonstate;
> class C
> {
>   // is passed an implicit nonstate pointer to the nonstate values
>   int f(int x) const
>   {
>       return nonstate[this] += 1;
>   }
> }

because this solution requires a non-trivial lookup time, whereas my 
solution does not require a lookup time.  Plus you have more synchronization 
to worry about (all instances must have a global mutex to the cache).  The 
point is, yes, you can solve it that way.  But why can't we have a way that 
has higher performance and less threading issues?  There is no reason I can 
see.

> If nonstate is not part of the object, why to put it in it? I this the
> cache-problem is a very specific problem, which is OK to have a specific
> solution. Even more, I find a lot more clear if the cache it's outside the
> class, because is not part of it (if it's not part of the state of the
> object, it's not part of the object at all!).

I agree it is confusing, but it's just a tacked-on piece that isn't part of 
the class, although it lives in the same allocated memory space.  What if I 
put it like:

class C
{
  nonstate
  {
     int c;
  }
  body
  {
     int f(int x) const
     {
        return nonstate.c++;
     }
  }
}

similar to how function contracts split the body from the contract.  Does 
this help your understanding?

what I don't get is how people can understand that static is not part of an 
instance, yet that goes into the class declaration, but they can't 
understand this.

> So C.f() is clearly not pure, but it's const, it doesn't change the state
> of the object.

Agreed.

-Steve 





More information about the Digitalmars-d mailing list