D const design rationale
Jascha Wetzel
firstname at mainia.de
Mon Jun 25 01:16:01 PDT 2007
Reiner Pope wrote:
> As storage classes, const and invariant both mean "compile-time
> constant" -- their initializers must be evaluatable at compile time, and
> their data need not be stored in memory.
the docs aren't very clear about that, but it's not fully correct when
you think about function parameters. the "initializers" of function
parameters are the arguments to the call, which need not be evaluatable
at compile time.
> void main() {
> int a = 10;
> int* p = &a; // here's our mutable view
> const int* cp = &a; // here's our const-as-storage-class
> }
>
> At the moment, this doesn't compile, because &a is not evaluatable at
compile time
it compiles when you change it to
int f(const int* cp) {
return *cp+3;
}
void main() {
int a = 10;
int* p = &a;
a = f(&a);
}
and it's also clear how *p can change here.
> [1] Although the data pointed to by const-as-storage-class *is*
> invariant, the type system doesn't believe it. The following doesn't
> compile (correctly so, according to the specs)
>
> const char[] a = "abc";
> invariant char[] b = a;
>
> but how can the data in 'a' possibly change?
again - if it is a parameter.
besides holes and overlap in the final/const/invariant keyword's
definition ranges, what is nice about D's const-system, is that while in
some situations A means the same as B, A always means A and B always
means B - unlike const in C++.
More information about the Digitalmars-d
mailing list