about the new const regime
Steven Schveighoffer
schveiguy at yahoo.com
Wed Jan 2 08:05:37 PST 2008
"Daniel919" wrote
>> 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)[]
c is not a copy of s or a reference to s. c references the same data that s
references. When you change s to reference different data, it does not
change c to reference this data. i.e. after the assignment, s.ptr != c.ptr.
Maybe this example will help:
int x = 5;
int *p = &x;
int *p2 = p;
writefln(*p, *p2); // outputs 55
int y = 6;
p = &y;
writefln(*p, *p2); // outputs 65
Assigning p to &y is similar to your code assigning s to "new".dup;
Now, if you modified a piece of the data s is pointing to, then c will
change. Try this:
s[0..3] = "new";
This copies the data from the array on the right into the array on the left
(I didn't yet compile this, so I'm not sure if it compiles as coded).
-Steve
More information about the Digitalmars-d
mailing list