Challenge: write a reference counted slice that works as much as possible like a built-in slice
deadalnix
deadalnix at gmail.com
Mon Nov 8 22:15:09 UTC 2021
On Monday, 8 November 2021 at 21:42:12 UTC, Andrei Alexandrescu
wrote:
> 1. We could not make reference counting work properly in pure
> functions (a pure function does not mutate data, which goes
> against manipulating the reference count).
>
I don't think this one is a real problem, as one can cast a
function call to pure and go through this. Dirty as hell, but
done properly it should work even in the face of compiler
optimization based on purity. GCC or LLVM would have no problem
optimizing this scafolding away.
> 2. Qualifiers compound problems with interlocking: mutable data
> is known to be single-threaded, so no need for interlocking.
> Immutable data may be multi-threaded, meaning reference
> counting needs atomic operations. Const data has unknown
> origin, which means the information of how data originated
> (mutable or not) must be saved at runtime.
>
shared_ptr does atomic operation all the time. The reality is
that on modern machines, atomic operation are cheap *granted
there is no contention*. It will certainly limit what the
optimizer can do, but all in all, it's almost certainly better
than keeping the info around and doing a runtime check.
> 3. Safety forced the use of trusted blocks all over. Not a
> showstopper, but a complicating factor.
>
> So if there are any takers on getting RCSlice off the ground,
> it would be very interesting.
Yes, similar to pure, a bit anoying, but workable.
I think however, you missed several massive problems:
4. Type qualifier transitivity. const RCSlice!T -> const
RCSlice!(const T) conversion needs to happen transparently.
5. Head mutability. const RCSlice!(const T) -> RCSlice!(const T)
conversion needs to happen transparently.
6. Safety is impossible to ensure without a runtime check at
every step, because it is not possible to enforce construction in
D at the moment, so destrcutors and copy constructor/postblit
always need to do a runtime check for .init .
I believe 4 and 5 to be impossible in D right now, 6 can be
solved using a ton of runtime checks.
More information about the Digitalmars-d
mailing list