about the new const regime
Steven Schveighoffer
schveiguy at yahoo.com
Wed Jan 2 06:26:15 PST 2008
"Daniel919" wrote
>> The difference is :
>>
>> string s = "bla";
>> s = "abc"; // compile, you can reassign to an invariant array with
>> another invariant array, but you can't change it partially.
>> s[0] = 'x'; //error as you said
>
> But the same is true for a const(char)[].
> const(char)[] s = "bla";
> s = "abc";
> s[0] = 'x'; //error
>
> const char[] s = "bla";
> s = "abc" //error
>
> invariant char[] s = "bla";
> s = "abc" //error
The difference is subtle. invariant means "nothing can change this". const
means "I can't change this".
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,
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