On Friday, 17 August 2012 at 03:57:21 UTC, Chris Cain wrote:
On Friday, 17 August 2012 at 03:42:23 UTC, Mehrdad wrote:
Yes, I 100% realize 'pure' and 'immutable' are advantages over
C++.
The question was about 'const' by itself, though, because
otherwise that's not a fair comparison. (The goal is comparing
C++ const to D const, not C++ const to D const + immutable +
purity.)
I don't know what to tell you then. If you have a non-const
pure function and add const to it, then you can make all kinds
of optimizations for free basically. But, as you've found, if
you completely ignore purity, you can find some ways around
that and the compiler would have to potentially perform some
expensive checks to do the same optimizations (unless they're
just not valid).
You can probably do more optimizations on primitive types
easier (but they obviously have their own limitations), but
many of those same optimizations could potentially be done on
C++'s const primitives as well. But really, the biggest
differentiation between C++'s const and D's const comes in to
play with non-primitives. C++'s const on classes, for instance,
gives you _no_ guarantees (none, at all, unless you dive into
the class and take a close look) and therefore _no_
optimizations without major costly calculations and certainly
no easy reasoning.
OTOH, D's const does give you guarantees. Combine that with
pure and you've got huge amounts of reasoning. And yes, I'd say
this answers your topic's question on what D's const does for
you. Clearly, a pure function without const doesn't provide you
with the same reasoning as a pure function with const.
writeln(s.pureMutatingFunc());
writeln(s.pureMutatingFunc()); // guaranteed not to change
globals ... restricted to only changing s and, transitively,
everything s points to
const: Prevents changing s and, transitively, everything s
points to (through the s view, of course ... doesn't say
anything about global data or other views available to you
because of global data, as you've found).
ergo, we can do this:
writeln(s.pureConstFunc());
writeln(s.pureConstFunc()); // definitely the same as above call
Now an impure function can modify globals, so it shouldn't
surprise you that if s has a pointer to a global, you can
modify the global and therefor the view s represents will also
have a change.
Okay so basically, the conclusion I'm drawing is that you have to
combine it with pure/immutable in order to get much more out of
it than compared with C++; otherwise, it's not really different.
Thanks!