Extended Type Design: further examples
Andrei Alexandrescu (See Website For Email)
SeeWebsiteForEmail at erdani.org
Mon Mar 19 17:50:28 PDT 2007
Derek Parnell wrote:
> Hmmm ... so the difference between 'const' and 'invariant' is that const is
> only effective for one level deep, but 'invariant' is effective for all
> levels, right?
Nonono. Const means: it might have originated as a variable, and
somebody, somewhere, might hold a mutating reference to this and call it
"my precious".
Invariant is: nobody ever holds a mutating reference to it.
Example:
void Fun(const char[] a, char[] b)
{
char c = a[0];
b[0] = 'z';
assert(a[0] == c); // will fail
}
void main()
{
char[] x = "Wyda".dup;
Fun(x, x);
}
Notice how the data referenced to by a is changing from under a's feet.
Now let's rewrite Fun:
void Gun(invariant char[] a, char[] b)
{
char c = a[0];
b[0] = 'z';
assert(a[0] == c); // never, ever, ever, ever fails
}
void main()
{
char[] x = "Wyda".dup;
Fun(x, x); // can't compile!
// mutating references can't be bound to invariant references
}
Andrei
More information about the Digitalmars-d
mailing list