Understanding the GC

monarch_dodra monarchdodra at gmail.com
Wed Jan 30 02:29:25 PST 2013


On Wednesday, 30 January 2013 at 08:15:15 UTC, Mike Parker wrote:
> On Wednesday, 30 January 2013 at 06:00:44 UTC, Jeremy DeHaan 
> wrote:
>
>>
>> From what I understand, when an object is recovered by the GC, 
>> the destructor may or may not be called. Why is that? Is it for
>
> That's not quite correct. When the object is collected, its 
> destructor will be called. But you have no control over when or 
> if it will happen during runtime. More on this below in 
> relation to your question about unreferenced objects.

To add to that, you also have to keep in mind that when the 
program terminates (even legally), instead of running a *full* 
collect cycle, the program just leaves, and lets the OS clear any 
allocated memory. This is both faster, and safer.

What this means is that while there is a guarantee that 
"collection=>destruction", there is no guarantee that actual 
collection will happen.

If you absolutely must be sure that something allocated gets 
*destroyed*, either destroy it yourself via an explicit call, or 
bind it to a stack based RAII scheme, possibly with reference 
counting.

>> performace reasons? What about the destructors of objects that 
>> the original object contained? Are they called when the item 
>> finally get's taken care of by the GC, or when the object is 
>> originally recovered by the GC?
>
> Destructors of members will not be called when an object is 
> collected. Only that of the object itself. But, there's no 
> guarantee that any member references will still be valid when 
> the object's destructor is called. See below for more.

Just to be clear, I suppose you (both) are talking about "member 
references"? EG: Nested classes?

Destroying an object 100% guarantees its member destroyers are 
also called, outer to inner, first in first out, as part of the 
destruction process. The thing is that when you store a "class 
reference" then you call the destructor of the reference itself. 
References being glorified pointers, it basically means it does 
nothing.

//----
struct S{}
class  A{}

struct/class SA
{
     S s; //destroying this means ~S gets called.
     A a; //"destroying" this means doing "a  = null".
}


More information about the Digitalmars-d-learn mailing list