GC-proof resource classes
cym13 via Digitalmars-d
digitalmars-d at puremagic.com
Sat Aug 29 08:20:23 PDT 2015
On Saturday, 29 August 2015 at 14:32:27 UTC, Timon Gehr wrote:
> But then classes with destructors shouldn't be allowed to be
> allocated on the GC heap in the first place, which is a PITA as
> well. (Note that classes/arrays can have destructors because
> some component structs have them; structs generally assume that
> their destructors will be called.)
I don't quite follow the reasonning here. If GC doesn't call the
destructor then this same destructor is no more than a normal
method (with restrictions... would those still stand?) that is
the default destruction method to be called by things like
scoped!T or destroy if explicit destruction is needed.
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?
Or do you fear for classes whose memory would be freed before
freeing its ressources? That could be a problem... In that case I
think the best option would be to allow them to be allocated by
the GC but GC-ing it if the destructor hasn't been called should
spawn an error (or something like that, haven't taken the time to
think through it). Or maybe it shouldn't be marked as garbage if
the destructor hasn't been called.
I think of it as a simple switch hasDestructorBeenCalled that
would be set to true if no destructor exists or if it has been
called, and false otherwise, and would prevent GC-ing (or
crash... I don't know what's best) of the object if false.
That way simple classes stay simple, complex classes can live on
the heap happily without fearing collection while being able to
reliably free ressources.
More information about the Digitalmars-d
mailing list