2.011 invariant question

Sönke Ludwig ludwig at informatik_dot_uni-luebeck.de
Sat Feb 23 03:58:51 PST 2008


I'm still trying to upgrade my code base from 2.008 and it's getting closer
with 2.011. However, there are some points left which make the porting quite
annoying, unfortunately. On of those points are structs with invariant members.

Maybe I'm missing something - but I don't get what's the reasoning behind the
following error?

-----------------
struct FOO {
	invariant int x;
	int y;
}

int main()
{
	FOO bar;
	bar.y = 2;
	return 0;
}
-----------------
gives the error:
test4.d(9): variable test4.main.bar cannot modify struct with immutable members



But on a related note on invariant - I think I have mentioned this already at
some point - but just in case. If 'invariant' should be theoretically safe in
the future, invariant values may not be allowed on the stack (the stack is never
invariant) - maybe something like "scope invariant" can be permitted - or some
heuristic which puts such values on the heap if a reference is takeen out of
scope (similar to closures). The same goes for invariant arrays and opCatAssign:

-----------------
import std.stdio;

int main()
{
	invariant(int)[] arr = [1, 2, 3];
	invariant(int)* someref = &arr[2];
	arr.length = 2;
	arr ~= 4;
	writefln("array: %s - %s", arr, *someref);
	return 0;
}
-----------------

prints "array: [1 2 4] - 4"

So currently any references to invariant data can be changed legally with
this stack principle. (Invariant arrays could be fixed by always reallocating on
opCatAssign)



More information about the Digitalmars-d mailing list