What guarantees does D 'const' provide, compared to C++?
Jonathan M Davis
jmdavisProg at gmx.com
Sun Aug 19 13:57:53 PDT 2012
On Sunday, August 19, 2012 22:14:49 Peter Alexander wrote:
> You only have that guarantee if there are no other mutable
> references to the data. const *on its own* does not provide that
> guarantee.
Yeah. If you really want to get down to the nitty gritty of when exactly the
compiler can guarantee that a const object won't change even through other
references, then you're restricted to cases where the compiler _knows_ that no
other mutable references exist, which is very restrictive. But in practice, it
buys you a lot more, and not only because of pure. For instance, if I have a
class that holds a container, and the only place that that data leaves my
class is its getter
@property const(Array!T) myContainer() const {...}
then I know that no one using the getter is going to mess with the container.
I know that there's no way that they can possibly screw with my container or
its contents via the getter. And since of course, I won't have written screwy
stuff into my class like having the container really point to a global or even
be set via a setter, I know that they won't even be able to mess with the
container via another reference. And if I control where the elements come
from, then I can know that the elements won't be messed with by any other
references either, because I'll know that there are no other references to
them.
Sure, the compiler may not be able to optimize much (if anything) there, but
it really helps you reason about your code - especially when it comes to
giving access to member variables to code outside your class or struct. So,
the combination of transivity and illegality of mutating const (even through
casting) does actually buy you quite a lot. Yes, adding in pure or immutable
buys you a lot more, but that doesn't mean that const is useless without them.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list