GC-proof resource classes

Jim Hewes via Digitalmars-d digitalmars-d at puremagic.com
Sun Aug 30 11:21:17 PDT 2015


On 8/29/2015 8:20 AM, cym13 wrote:
> I think there should be a separation of concerns that isn't possible
> right now. Freeing ressources and freeing memory isn't the same thing
> and they should be decoupled. I think a destructor is there to free
> ressources, and the GC is there to free memory. If the GC doesn't call
> the destructor then why should having a destructor have anything to do
> with the GC?

This.

I think when language designers consider reference counting vs. garbage 
collection in the beginning, they decide that reference counting is too 
costly, particularly in cases where you may need to create many small 
objects. So garbage collection seems to make more sense if you have to 
choose one or the other. But the places I want deterministic destruction 
always tend to be when there are only one or a few objects because they 
are handles or wrappers for resources which aren't very numerous. So the 
cost of reference counting is negligible and is worth it in these cases. 
But unfortunately this problem got swept under the rug with garbage 
collection.

I confess I haven't thought about this in depth and surely other people 
have; so there may be reasons why this is a more difficult problem than 
I think. But I agree there should be a separation of concerns between 
memory and other resources. But there may need to be some sort of 
transitivity with it, similar to const/immutable. That is, if I have an 
object which needs reference counting---for which the resources need to 
be cleaned up---and it is a member of another object, then the owning 
object also needs to be reference counted automatically or made to be a 
compiler error. Whether this is implicit just by having a destructor 
defined or explicit I'm not sure. I just don't know if this could be 
handled at all with collection classes. (How would they know?)

Does it make sense that this needs to be tied to structs and not 
classes? I'm not a language designer so I don't know the reasons. But 
ideally I'd think the whole concern of releasing resources would also be 
separate from that as well.

Regarding the garbage collector, if the destructor isn't guaranteed to 
be called, then I have to assume the worst case that it won't be called. 
That means I should not use destructors in these cases. It seems to me 
that should be enough argument.



More information about the Digitalmars-d mailing list