I just got it! (invariant/const)

Georg Wrede georg at nospam.org
Wed Apr 9 09:48:01 PDT 2008


Janice Caron wrote:
> On 09/04/2008, Denton Cockburn <diboss at hotmail.com> 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.

It should be illegal to cast objects invariant unless the compiler can 
guarantee the invariantness. So the cast here should produce an error.



More information about the Digitalmars-d mailing list