about the new const regime

Daniel919 Daniel919 at web.de
Wed Jan 2 06:47:54 PST 2008


> The difference is subtle.  invariant means "nothing can change this".  const 
> means "I can't change this".
.. from this pointer/ref.
So I can read this only from this pointer/ref.
Ok, I already posted some thoughts about it under this topic.

> So for a const array, for instance:
> 
> char[] s = "bla".dup;
> const(char)[] c = s; // ok
> invariant(char)[] i = s; // error
> invariant(char)[] i2 = c; // error
> 
> This is an error because since you could potentially change i by changing s, 
Tried it:
char[] s = "bla".dup;
const(char)[] c = s;
writefln( c ); //bla
s = "new".dup;
writefln( c ); //bla
So c got a copy of s. But then, how can I change c by using s?
If I can't, then I see no difference to invariant(char)[].
If c was a reference to s, then it would make sense to distinct between:
1. can't change the data of c via c = const(char)[]
2. data of c will never change = invariant(char)[]

> you can't assign s to i or c to i without an explicit cast.  The explicit 
> cast tells the compiler you are ensuring that s will no longer be changed by 
> anything:
> 
> invariant(char)[] i3 = cast(invariant(char)[])s; // ok
> 
> This is ok, but you can no longer change s.  If you do, the behavior is 
> undefined.
> 
> Do you see the difference now?  In most cases, if you are initializing a 
> const variable with a literal, or a new() statement, you can change the 
> modifier to invariant because logically, nothing can change that variable. 
> It would be nice if the compiler automatically did this for you, but I don't 
> think this is the case today.
> 
> -Steve 
> 
> 



More information about the Digitalmars-d mailing list