Want reasonable reference counting? Disable automatic sharing of immutable

Steven Schveighoffer schveiguy at gmail.com
Fri Nov 12 12:31:03 UTC 2021


One of the prerequisites to doing reference counting is to have a 
mutable piece of data inside an immutable piece of data.

A few years ago, Timon Gehr implemented a concept for `__mutable` that 
looked like it might be the answer. But there was a large problem. As 
the title suggests, it's because immutable is implicitly sharable.

This makes sense in a world of fully transitive immutable, where if you 
have an immutable pointer, nothing in it can ever change. But if you 
have a `__mutable` island, that can change. So the answer at the time 
was, `immutable(__mutable)` -> `shared`.

Unfortunately, this means you have to apply it to `const` as well, 
because `const` could be pointing to `immutable`. I'll note that this 
still might be a valuable concept, just slightly annoying, especially 
with `shared` becoming more tightly controlled.

I thought of an idea -- maybe you make it so if a type `T` had a 
`__mutable` piece, you can't share an `immutable(T)`. This actually 
works quite well, and now you have to explicitly have 
`shared(immutable(T))` in order to share it.

But there is a rather large problem -- classes. Classes might have a 
`__mutable` buried in a derived object that the compiler isn't aware of. 
So that is a no-go.

Another possibility is to introduce new type qualifiers, like 
immutable-with-mutable or const-with-mutable, which are not shared, but 
I feel like the appetite for new qualifiers is pretty low, and the names...

I've come to the conclusion, in order to fix this situation, so 
`__mutable` really means mutable and `shared` is an orthogonal piece, 
you need to remove the implicit sharing of `immutable`. While it can 
make sense, the conflation of the two concepts causes impossible-to-fix 
issues. Not just mutable, things like thread-local garbage collection 
might be easier if you have to explicitly share things.

-Steve


More information about the Digitalmars-d mailing list