Are D classes proper reference types?
Ola Fosheim Grøstad
ola.fosheim.grostad at gmail.com
Sat Jun 26 07:00:37 UTC 2021
On Friday, 25 June 2021 at 23:55:40 UTC, kinke wrote:
> I cannot imagine how weak pointers would work without an ugly
> extra indirection layer. If we're on the same page, we're
> talking about embedding the reference counter *directly* in the
> class instance, and the class ref still pointing directly to
> the instance.
So, my understanding is that C++ `make_shared` may allocate the
reference chunk and the object in the same memory area, so that
the reference count/weak counter is at a negative offset. That
way you can free up the object while retaining the counter. (At
some fragmentation cost, if the counter isn't freed.) This may
give some cache advantages over separate allocation.
Maybe @weak could be an annotation, but I haven't given this much
thought. If we think about it; You don't have to pass around weak
pointers, so there is no reason for parameters to be marked weak?
Only pointer-fields in structs or classes? In function bodies you
would typically not want to use a weak pointer as you want to
extend the lifetime of the object until the function returns.
Also you could mark a class as non-weak, to save the weak counter.
> Weak pointers aren't in the language, so I don't see why they
> would matter here. I thought you were after replacing
> GC-allocated class instances by a simple RC scheme.
One goal could be to make a class compatible with C++ or Swift on
request. Both support weak pointers. You could have multiple
ref-count layout schemes as long as they all are on negative
offsets. Just don't mix class hierarchies. So you could mix a D
class hierarchy, C++ class-hiearchy and Swift class-hierarchy in
the same codebase?
> In modern C++ code I've been looking at so far, shared_ptr was
> used very rarely (and unique_ptr everywhere). AFAIK, the main
> reason being poor performance due to the extra indirection of
> shared_ptr. So replacing every D class ref by a
> shared_ptr-analogon for interop reasons would seem very
> backwards to me.
In C++ ownership should in general be kept local and one should
use borrowing pointers (raw pointers) for actual computations, so
only use owned pointers for transfer of ownership. But that puts
more of a burden on the developer.
More information about the Digitalmars-d-learn
mailing list