Extended Type Design: further examples
Andrei Alexandrescu (See Website For Email)
SeeWebsiteForEmail at erdani.org
Mon Mar 19 18:38:41 PDT 2007
Derek Parnell wrote:
> On Mon, 19 Mar 2007 17:50:28 -0700, Andrei Alexandrescu (See Website For
> Email) wrote:
>
>> 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.
>
> Yeah ... but that's not what I was talking about. But be that as it may, it
> seems you are saying that the *only* difference between 'const' and
> 'invariant' is that 'invariant' means that every write attempt (direct and
> indirect) is denied, but 'const' only prevents direct write attempts.
>
> By 'direct' I mean explicitly using the symbol in the statement, and not
> another symbol that happens to contain the same address of the data.
>
>
> But I was talking earlier about the situation where something contains
> reference types or structs, and what effect 'const' and 'invariant' have on
> the things indirectly accessible via member data.
>
> struct Foo
> {
> char[] s;
> }
>
> void Func(const Foo fc, invariant Foo fi)
> {
> fc.s = "abc"; // fails ???
Works. Understand that fc is the private copy owned by Func.
> fc.s[0] = 'a'; // okay ???
Fails. fc would change bits not belonging to itself, and "const" makes
those bits unchangeable.
> fi.s = "abc"; // fails ???
Works. Modifies Func's own private copy of fi.
> fi.s[0] = 'a'; // fails ???
Fails.
> }
>
> Foo a;
> Foo b;
> Func(a,b); // fails ???
Fails. Can't bind modifiable b to an invariant Foo.
> const Foo ac;
> const Foo bc;
> Func(ac,bc); // fails ???
Fails. Can't bind const b (which conservatively may be aliased to a
modifiable view) to an invariant Foo.
> invariant Foo ai;
> invariant Foo bi;
> Func(ai,bi); // fails ???
Works. No problem to bind ai to a const Foo.
> Func(ac,bi); // okay ???
Perfect.
Andrei
More information about the Digitalmars-d
mailing list