Invariant Question (yes, another one)

Janice Caron caron800 at googlemail.com
Thu Nov 15 08:22:13 PST 2007


On 11/15/07, Matti Niemenmaa <see_signature at for.real.address> wrote:
> If I understood correctly:
>
> An invariant variable cannot change, period. If you cast an invariant variable
> to const, and then change it through the const variable (this bit seems dubious
> to me), the invariant variable has changed. But this isn't permissible. Hence,
> you can't cast invariant to const.

Ah! I'm afraid you're wrong.

You /can/ cast from invariant to const - and in fact, this kind of
cast is IMPLICIT. For example:

    invariant(char)[] s = "hello";
    const(char)[] t = s; /* OK - compiles fine */

What you cannot do is "change it through the const variable". That's
illegal. Absolutely illegal. In the docs, Walter says it is
"undefined". Short version - never do this!

    char[] u = cast(char[]) s; // BAD!

(The slightly longer version is you actually can do that if you
really, really know what you're doing, and you've got mutex locks and
such to absolutely guarantee well-defined behaviour, but it's not for
the faint-hearted).



More information about the Digitalmars-d mailing list