Invariant doesn't apply to declared symbols

Janice Caron caron800 at googlemail.com
Fri Nov 30 01:08:50 PST 2007


Let's consider how this would be done in C++. To get a class on the
heap, you'd do

    C * c = new C();

To make the data only const, you'd do

    C const * c;

(or "const C * c" but let's not go into C++'s confusing alternatives
here). To make both the data and the pointer const, you'd do

    C const * const c;

(or "const C * const c" but again, let's not go into C++'s confusing
alternatives here). If classes in D used the syntax of pointers, it
would be easy. We could say:

    const(C)* // just the data is const
    const(C*) // the data and the pointer are both const

Unfortunately, that won't fly, because we /don't/ use pointer-syntax.
The pointer is /implicit/. So the dereferencing asterisk is also
implicit. It's a nasty problem for us, because of course we still want
the declaration to read like we're declaring a variable c with type C
(with some degree of constness applied somewhere). So any syntax which
makes that NOT obvious is one we should be wary of. Suggestions like

    const(&C) c

don't work for me, because it looks like we want c have type "address of C".

Fortunately, there is an answer. Well, we may not have pointers, but C
is a reference type, right? And we do have the "ref" keyword. Thus, we
could distinguish

    const(C) // just the data is const
    const(ref C) // the data and the pointer are both const

That one /kind of/ works - but it does violate the principle that

    const(T) x;
    x = y;

should always be a compile error. (If x is fully const, how can it be
assigned?). So here's my latest and greatest idea. What about:

    const(C)ref // just the data is const
    const(C) // the data and the pointer are both const

This would give us

    const(C) c;
    const(C) ref d;

    c = new C: // Error;
    d = new C; // OK
    d.x = 100; // Error

That one works for me. It's my favorite suggestion so far. It does
what we need, /and/ it allows const to follow a general pattern.



More information about the Digitalmars-d mailing list