about the new const regime
Daniel919
Daniel919 at web.de
Wed Jan 2 08:39:50 PST 2008
> 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).
writefln( c ); //test
s[0..3] = "new";
writefln( c ); //newt
This made it clear, shows that c is not a copy of s.
And as expected:
c[0..3] = "new";//Error: slice c[cast(uint)0..cast(uint)3] is not mutable
const(char)[] c = s;
elements c refers to can't be changed via c
invariant(char)[] i = s;
elements i refers to will never change
Thanks for your explanation.
More information about the Digitalmars-d
mailing list