Invariant doesn't apply to declared symbols
Walter Bright
newshound1 at digitalmars.com
Fri Nov 30 02:58:11 PST 2007
Jason House wrote:
> This is the one thing that really bugs me about const...
>
> The docs say that the following is legal
> invariant(S) s;
> s = ...; //legal
Yes.
> This seems to add logical inconsistency...
>
> invaraint(int*) p;
> p = ...; //legal
>
> invariant(char*)** p;
> **p = ...; //illegal
>
> It seems that invariant(T) changes based on context! (All examples above
> come from http://www.digitalmars.com/d/const3.html)
No. See my other reply to Janice, what we have here is a rebindable
variable.
> Unfortunately, it doesn't stop here for me.
>
> It seems that "const(char) *p;" and "const(char*) p;" have identical
> meanings even though the syntax is different.
No, the types are different. If you take the address of p, you'll see
the type difference.
> Also, "const(char) p;" and "const(S) s;" have different meanings. In the
> first, assignment to p is disallowed. In the second, assignment to s is
> allowed.
Not true, assignment to both is allowed. To disallow rebindable
variables, give them const storage class.
> When going into generic coding or upgrading to more complex data
> types in code, this type of thing *has* to bite someone eventually.
>
> Also, how I define a const point to const data? As I understand it, this is
> impossible. "const int* p;" and "const(int*) p;" both mean a non-const
> pointer to const data. While I don't explicitly see const(T) being the
> same as const T in the docs, Walter has said this on the NG.
No, the types are the same, but the storage class is different.
> All of this leads me to ask wonder why this style of functionality is done.
> It seems like a whole lot of ambiguity just to allow "const(S) s;" to have
> constant members but a non-constant reference.
Consider const(C) where C is a class type. If declarations of type
const(C) were not rebindable, they become impossible to use.
> I appreciate the argument that "const(S) s" is all that is syntactially
> available without any modification, but I encourage some thought into using
> a novel syntax for this. I have not come up with a good syntax for this.
> The best I've got is
> const(S) s; // can not assign to s or s.foo
> const(S)& s; // can assign to s, but not s.foo
> const(S)* s; // can assign to s, but not *s
>
> I think the last case may be the common case for working with foreign (C?)
> API's. I will admit to not understanding the argument of "in order to use
> structs as wrappers for builtin types, ...". I don't know of a common use
> case for this.
It's much simpler:
const(S) s; // can rebind s
const S s; // cannot rebind s
More information about the Digitalmars-d
mailing list