What guarantees does D 'const' provide, compared to C++?
Chris Cain
clcain at uncg.edu
Thu Aug 16 21:15:00 PDT 2012
On Friday, 17 August 2012 at 03:44:38 UTC, Mehrdad wrote:
> To clarify... the motivation for this question in the first
> place was the fact that I've been consistently told (and have
> read) that D const provides more guarantees than C++ const, so
> I was trying to figure out how.
>
>
> If what you're saying is that the extra guarantees only
> translate into optimizations when used along with
> immutable/pure, then that's a completely valid answer. :) Is
> that what you're saying?
>
> (i.e. I DO realize that combining them would give you an
> optimization, but the question is -- must you combine const
> with something else to gain an advantage over C++?)
Well, I guess if you're modifying globals and you're going to
have your object pointing to those globals, then no you aren't
going to get any optimizations that way. And code like that will
be harder to reason about as well. I'd have a hard time saying
that the "extra guarantees only translate into optimizations when
used along with immutable/pure". I'd say in more realistic code
where you don't do absurd things like intentionally put a global
into a const variable just to mutate the global willy nilly,
you'd get optimizations (although, it'd probably have to check
for those absurd cases as well, but non-trivial optimizations are
still optimizations and it's possible to do).
It is something that would be much more difficult to do with C++
... so much so, that if C++ didn't have the const keyword, I'd
imagine the problem would still be roughly the same difficulty.
Not only does C++ have to check globals like D would, but it has
to check to make sure none of the mutable-marked member variables
change, and if they do, then it would have to check to make sure
that the change wouldn't result in changes in other functions
(even if they're const functions, btw) along the way and ... etc.
But yeah, you do get guarantees with D's const that you don't
with C++ const (mutable keyword, again, which makes C++'s const
useless in all non-trivial cases).
I will say that D's features have a synergy about them and
combining them with another one will make them more powerful than
the two individually. So const + pure is a pretty good
combination. That does make many optimizations (that would
normally be difficult) completely trivial to do.
More information about the Digitalmars-d
mailing list