D const design rationale

Christopher Wright dhasenan at gmail.com
Sat Jun 23 19:07:48 PDT 2007


Martin Howe wrote:
> After reading the articles by Walter referred to recently, I'm less confused 
> that I was, but would still appreciate some further explanation.
> 
> So should "const foo bar = baz" be an error if foo is a value type, on the 
> basis that one should be using "invariant" or maybe final? It it safe to 
> have two things const/invariant that become identical depending on type?

For value types, there's no difference between const, final, and 
invariant. So it's not an error.

This is probably the most confusing part of the whole deal, and there's 
no way around it except by making all value types into reference types 
(ugh) or vice versa (but we've progressed beyond C).

> And does "final" exist *solely* so that you can approximate "invariant" for 
> objects as well as for structs and scalars? I can see its use when you want 
> something to be invariant but with the stipulation that it must exist in 
> memory and have an address. In which case, why have final vs invariant at 
> all, rather than having final be, for example, "weak invariant" or "stored 
> invariant" or something like that? From here, final just looks 
> *semantically* like "a poor man's invariant".
> 
> 

Not at all. A final variable cannot be reassigned; the reference is 
const, but the data is mutable.

So:
---
class Foo {
    int _bar;
    public void bar(int value) { _bar = value; }
}

final Foo foo = new Foo();
foo.bar = 5; // legal -- I'm not touching the reference
foo = new Foo(); // fails -- foo was already assigned
---



More information about the Digitalmars-d mailing list