DIP74 - where is at?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sun Oct 11 15:33:42 PDT 2015


On Sunday, 11 October 2015 at 22:12:50 UTC, Ola Fosheim Grøstad 
wrote:
> On Sunday, 11 October 2015 at 21:15:38 UTC, Jonathan M Davis 
> wrote:
>> In this case in C++, because the ref-counting is not built-in 
>> to the type, there is no way for the Child to have access to 
>> its parent via a shared_ptr. It has to be done via a normal 
>> pointer. D has exactly this same problem. If the ref-counting 
>> isn't built-in, then there are cases where you have to let a 
>> non-ref-counted reference escape.
>
> In this case one should use unique_ptr, so the D discussion 
> about ref counting is irrelevant. If you have truely shared_ptr 
> semantics and back pointers, then one shoud use weak_ptr for 
> this since the back pointers don't own the resource. Keep in 
> mind that shared_ptr only denote ownership, not resource usage.

I don't want get into arguments about smart_ptr and unique_ptr. 
It's completely irrelevant to my point.

weak_ptr doesn't work when the child is constructed by the parent 
in the parent's constructor. The fact that the parent does not 
have access to the smart pointer type that it's about to be put 
into means that it cannot give that to the child. It has to give 
it a normal pointer. And that means that you can't make it so 
that all accesses to the parent object are via a smart pointer. 
And in the case of D, that means that it doesn't work to restrict 
all access to a class object to a wrapper struct like RefCounted, 
and it becomes quite easy for a reference to the class object to 
escape the wrapper struct. And that means that it's not @safe, 
because the wrapper struct might destroy the class object when 
it's destroyed (because its ref-count reached 0) while a 
reference to that class object is still floating around 
somewhere. Obviously, it can work (it works in C++). It just 
means that it can't be @safe and that the programmer has to worry 
about ensuring that memory doesn't get used incorrectly. But part 
of the whole point of DIP 74 is so that we can have @safe 
ref-counting in D.

- Jonathan M Davis


More information about the Digitalmars-d mailing list