I just got it! (invariant/const)

Steven Schveighoffer schveiguy at yahoo.com
Wed Apr 9 07:28:18 PDT 2008


"Janice Caron" wrote
> On 09/04/2008, Denton Cockburn wrote:
>>  > Of course, the explicit cast necessary to
>>  > create an invariant C in the first place is a bit ugly. Maybe we need
>>  > "inew" to make new invariant objects?
>>
>> Couldn't the compiler insert the cast based on the declaration?
>
> No, because objects created by new are not necessarily transitively
> unique. For example
>
>    class C
>    {
>        int * p;
>
>        this()
>        {
>            p = &someGlobalVariable;
>        }
>    }
>
>    invariant C c = cast(invariant) new C;
>    someGlobalVariable = 1;
>
> Whoops! c just changed!
>
> The explicit cast makes it the programmer's fault, not the compiler's!
>
> Come to think of it, "inew" would suffer the exact same problem, so it
> doesn't solve anything. Looks like there's no easy way to make an
> invariant class instance.

Sure there is :)

class C
{
   int *p;
   int q;

   invariant this() // means, 'this' is going to be invariant
   {
       //p = &someGlobalVariable; // fails, p must point to invariant
       q = 5; // allowed by compiler because it's the first time you set q.
       p = &q; // allowed because q is invariant.
   }
}

I think this was outlined in Andrei's presentation about grafting functional 
languages onto imperitive languages.

Of course, it doesn't work today, but I think it would work.

In fact, I think if you have a class like:

class X{}
class C
{
    invariant X x;
}

There is no way to set x anywhere...  I think this needs to be addressed.

-Steve 





More information about the Digitalmars-d mailing list