Invariant Question (yes, another one)

Regan Heath regan at netmail.co.nz
Thu Nov 15 07:36:03 PST 2007


Janice Caron wrote:
> On 11/15/07, Xinok <xnknet at gmail.com> wrote:
>> Const is the read-only type, meaning that the data COULD change
>> unexpectedly. However, invariant means the data is guaranteed never to
>> change. You can't guarantee const data is never going to change,
> 
> I know that. You're stating the obvious.
> 
>> which
>> is why it gives you an error.
> 
> I don't follow that reasoning. Please explain in more detail.
> invariant(char)[] can always be implicitly cast to const(char)[] ...
> and that's exactly what I'm trying to do.

Yep.  You know all this already but this might be of interest to others...

http://www.digitalmars.com/d/final-const-invariant.html

"Implicit Conversions

Mutable and invariant types can be implicitly converted to const. 
Mutable types cannot be implicitly converted to invariant, and vice versa. "

It makes sense to allow a read-only view (const) of data which cannot 
change (invariant), just as it makes sense to allow a read-only view of 
data which can.  In fact it's irrelevant whether the data can or cannot 
change because all const promises is that changes wont occur via the 
const reference itself.

Returning to the problem at hand... Steven makes a good point.  The AA 
itself is not invariant, or const.  So, suppose you have:

void main()
{
	char[] bob = "bob".dup;
	char[] fred = "fred".dup;

	invariant(char)[][invariant(char)[]] iaa;
	const(char)[][const(char)[]] caa;

	iaa["hello"] = "world";
	caa = iaa;  //pretend this is allowed

	caa[bob] = fred;
}

Now iaa contains bob and fred which are not invariant.

Regan



More information about the Digitalmars-d mailing list