D const design rationale
Don Clugston
dac at nospam.com.au
Fri Jun 22 02:05:18 PDT 2007
Walter Bright wrote:
> http://www.digitalmars.com/d/const.html
It's a good article. However, it could really use some examples. The article on
scope was very convincing because it gives plausible use-cases. In particular, I
think there needs to be an example for 'invariant'. When is 'const' not good enough?
Where you state that invariant solves the aliasing problem, you could prove it
by rewriting the example from the C++ section.
QUOTE ---
But there is a need for a constant declaration referencing a mutable type.This
is provided with the final storage class for declarations...Its main purpose is
...[that it]...can be mentally separated from variable declarations that are
meant to change
---
I don't find this very convincing. Is the mental benefit really significant
enough to justify the extra complexity? The existence of three const-related
keywords is pretty tough on mental space!
QUOTE ----
int x = 3;
const int *p = &x;
*p = 4; // error, read-only view
x = 5; // ok
int y = *p; // y is set to 5
This is one instance of the so-called aliasing problem, since while the above
snippet is trivial, the existence of such aliases can be very hard to detect in
a complex program. It is impossible for the compiler to reliably detect it. This
means that the compiler cannot cache 4 in a register and reuse the cached value
to replace *p, it must go back and actually dereference p again.
---
Shouldn't that be: "the compiler cannot cache 3 in a register" ?
More information about the Digitalmars-d
mailing list