mutable keyword

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 20 13:55:42 PDT 2016


On Friday, May 20, 2016 19:33:49 Johan Engelen via Digitalmars-d-learn wrote:
> On Thursday, 19 May 2016 at 23:21:14 UTC, Jonathan M Davis wrote:
> > No. D's const and immutable provide no backdoors. Rather, they
> > provide strong guarantees. So, if a variable is const, then it
> > cannot be mutated (even internally) except via a mutable
> > reference to the same data.
>
> The "even internally" is incorrect, and I think needs fixing:
> currently you can synchronize on an immutable/const object, but
> the synchronize implementation will write to __monitor inside the
> object (the field after vptr) and gone is the guarantee. This
> means that you cannot put immutable objects in readonly data, for
> example. We had to make TypeInfo objects mutable in LDC exactly
> because of optimization errors due to this const guarantee
> breakage.
> I still have to write up a detailed bug report about it...

The whole monitor thing is was a mistake, and I believe that it's pretty
much been agreed upon that we should rip it out, but no one seems to have
actually finished the job yet. IIRC, the proposal was to replace it with an
attribute such that if you used the attribute, then you get more or less
what we have now, but if you don't, then the class in question has no
monitor.

But whenever you have a monitor, you're in pretty much the same boat as with
something like having ref-counted in the language like Andrei wants added,
and you use it with immutable. If you want it to work, then the ref-count
needs to be outside of the object rather than in it, since the memory of the
object has to be treated as immutable. But if that almost certainly means
putting the ref-count (or monitor) next to the object in memory, which would
likely still prevent putting the object in ROM even though the object itself
would then be properly treated as immutable. But at least that would be
opt-in, whereas the monitor mess as it is now is not.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list