const(FAQ)

Kevin Bealer kevinbealer at gmail.com
Mon Mar 31 21:31:53 PDT 2008


guslay Wrote:

> I think we are agreeing on the benefits of "pure" methods.
> 
> But arguing that an immutable object is automatically thread-safe is simply not true under the current definition of const. It's an over-generalization. It's just one part of the puzzle.
> 
> A pure methods has to be const, but a const method is not implicitly pure.

I think what you're saying is right, and I think we can probably stop arguing since
I think there is wisdom in each approach.... I think.

In fact I could suggest a fourth variety of D const that worked like C++ const, but
since there are already at least 3 of them, I would probably get rotten fruit thrown
at me ... so I won't.

Regarding the D approach then:

I think it is a question of cooperation and goals.  If you have a method in D that only
operates on in-class data then it is pure.  (It can also operates on other classes but
only if it only calls methods following the same "pure" rules, and they do the same,
recursively.)  Many methods like .size() can easily be pure since they operate entirely
within the object, so in practice this is quite feasible.

The D const system does not prove purity, but it helps a lot when writing code and
making it pure.  The C++ const gives every class the tools and therefore implicitly 
the permission to use mutable fields in const objects, which means that if people
do things in a non-pure way its not even wrong.  In fact my (limited) understanding
is that the C++ standard actually supports the idea of casting away const just to
side step the const regime.

It's kind of like garbage collection -- you can have garbage collection in C++ but its
risky because it has to be conservative and no existing class expects to run under
a GC regime.  In D its a conservative system in just the same way, but because it
is part of the language, the assumption and the APIs suggest that you shouldn't do
certain things.  So in D, if you do something that not GC compatible, breaking the
code, then its *your fault*, whereas in C++ you could justifiably ask "what do you
mean, GC?"

If D can establish an understanding (i.e. best practices) that say "don't use mutable 
external stuff from a const method in a way that impedes purity" then there is a real
possibility for more multithread-safe code.  There has to be understanding that if

int x;
class ... {
...
const int size() { return ++.x; }
};

does not work, its the authors fault.  But maybe a full-fledged "pure" is a better
approach, but that would prevent a lot of things like output to "stdout", which is
not pure but which can be proven not to deadlock.

Kevin




More information about the Digitalmars-d mailing list