destructor order

Steven Schveighoffer schveiguy at yahoo.com
Wed Jan 26 08:01:19 PST 2011


On Wed, 26 Jan 2011 10:53:29 -0500, Albin Breen <abreen at ea.com> wrote:

> Steven Schveighoffer Wrote:
>
>> See here: http://www.digitalmars.com/d/2.0/class.html#destructors
>>
>> "The garbage collector is not guaranteed to run the destructor for all
>> unreferenced objects. Furthermore, the order in which the garbage
>> collector calls destructors for unreference objects is not specified.  
>> This
>> means that when the garbage collector calls a destructor for an object  
>> of
>> a class that has members that are references to garbage collected  
>> objects,
>> those references may no longer be valid. This means that destructors
>> cannot reference sub objects."
>
>
> Thanks! This means that the GC cannot be trusted to call destructors. I  
> interpret that as "class destructors must be called manually".
>
> Furthermore, The D Programming Language book states that: "...there is  
> no delete operator. (D used to have a delete operator, but it was depre-  
> cated.)" so you can't use that either.
>
> In other words you are left with:
> 	clear(a);
> to manually call the destructor, which will also call the constructor  
> again (this time with no parameters), and possibly (but not certainly)  
> the destructor once more.
>
> To be able to use clear() you will have to enforce RAII using structs  
> (not garbage collected) or finally{} or scope constructs all the way  
> from main in parallel with all your garbage collected code.

That is a misdesign in clear.  It should destroy an object and not  
initialize it again.  Furthermore, the destructor should only be called  
once.

Andrei agreed to make that change, but it hasn't gone in yet.

-Steve


More information about the Digitalmars-d mailing list