Destructor order

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 18 08:59:46 PDT 2016


On 3/18/16 11:07 AM, Andrea Fontana wrote:
> On Friday, 18 March 2016 at 15:03:14 UTC, Steven Schveighoffer wrote:
>> Structs are contained completely within the class instance memory
>> block (e.g. the OP's code). Classes are references. They are not
>> destroyed when you destroy the holder, that is left up to the GC,
>> which can destroy in any order. And in fact, it's a programming error
>> to destroy any GC-allocated memory inside your dtor, because it may
>> already be gone!
>>
>
> Not the case. I'm writing a binding for a library. Class A and B wrap
> c-struct and on d-tor I have to free underlying c object calling
> c-library destroyer. I'm not destroying any d/GC-allocated object. But
> of course i have to destroy c object in the correct order... How to?

Then you need to reorganize how they are related. Even though class B 
wraps a C resource, it's still stored on the heap, and can be destroyed 
in any order.

I'd recommend ensuring the dependency requirement is implemented within 
one object. Either make B a struct member, or have the destruction done 
by a third object.

-Steve



More information about the Digitalmars-d-learn mailing list