Casting const/invariant

Daniel919 Daniel919 at web.de
Thu Jan 3 08:40:52 PST 2008


Janice Caron wrote:
> On 1/3/08, Daniel919 <Daniel919 at web.de> wrote:
>> When creating a new invariant struct/class, the compiler can always
>> infer a cast(invariant).
>> invariant clFoo foo = /*cast(invariant)*/ new clFoo();
> 
> I don't believe that is true. Consider
> 
>     class C
>     {
>         int *p;
>         this() { p = &some_global_variable; }
>     }
> 
> I don't see anything to stop *C.p from being modified by another means.

import std.stdio;

int some_global_variable = 1;

/*invariant*/ class C
{
	int *p;
	this() { p = &some_global_variable; }
}

void main()
{
	invariant C c = /*cast(invariant)*/ new C();
//Error: cannot implicitly convert expression (& some_global_variable) 
of type int* to invariant(int*)

	invariant C c = cast(invariant) new C();
//OK, you promise not to change some_global_variable anymore

	writefln( *c.p );
	some_global_variable = 2;
//undefined behavior, you lied
	writefln( *c.p );
}


The inferred cast(invariant) would mean the same as
declaring the struct/class "invariant" for this new object.
So it would ensure that everything is deep invariant.

An explicit cast(invariant) on an existing reference is different.
There might be pointers/refs that point to mutable data. But we
ensure that this data will not change anymore.



More information about the Digitalmars-d mailing list