Right now, what's the most important for the success and adoption of D?

Bill Baxter dnewsgroup at billbaxter.com
Sun Sep 30 00:16:23 PDT 2007


Daniel Keep wrote:
> 
> Patrick Kreft wrote:
>> Am 29.09.2007, 16:03 Uhr, schrieb Daniel Keep
>> I know so long exist an instance of MyClass so her resource will exist
>> too, or the GC is useless cuz he make man class useless.
> 
> Yes.
> 
>> Or i can not use that:
>>  class MyClass
>>  {
>>      OtherClass a;
>>      this() {
>>         a = new OtherClass;
>>      }
>>
>>      void doit()
>>      {
>>     a.call() // scasm: opps a was deleted from GC Error eh?
>>      }
> 
> I really hope that "scasm" isn't meant to be "sarcasm".  That line is
> fine, but...
> 
>>      ~this() {
>>         delete a;
>>      }
> 
> This is wrong for exactly the reasons I stated before.
> 
> The problem is that you *cannot guarantee what order objects are
> destroyed it*.  This means that by the time "delete a" is called, "a"
> may have already been destroyed.
> 
> To put it in more concrete terms, the GC is free to destroy objects
> (assuming the instance of MyClass is called "this") either:
> 
> 1. "this" followed by "a", which means ~this works just fine, *or*
> 2. "a" followed by "this", which will probably cause a segfault.
> 
> You *cannot* tell which of those two will happen.
> 
> In general, you *must not* attempt to delete, read or write fields or
> call member functions of objects inside a destructor.
> 
> As downs said, it sucks.
> 
>>  }
>>
>> Look an http://www.digitalmars.com/d/garbage.html
>> the GC use Reference counting that mean so long a is not noll, it will
>> never delete.
> 
> Um, *no*.  The D garbage collector does *not* use reference counting; I
> have no idea where you got that from.  The D garbage collector uses a
> conservative mark-and-sweep algorithm, which means when a collection
> occurs, it scans memory starting at the roots (which are the call stack
> and global data).
> 
> 	-- Daniel


And if you want to know why this is true, here's the way I understand 
it.  If I'm wrong someone please correct me.

Basically when asked to collect, the GC first goes through and does 
"mark" phase where it marks things that it finds are still referred to 
(I think this is a recursive thing, starting with global variables and 
stack variables, marking what they refer to, then marking what those 
things refer to and so on.)  Then the next step is "sweep".  The GC goes 
through *all* the memory it knows about and any objects that aren't now 
marked must be unreachable, so it just reclaims them in the order it 
finds them.  This is why an object and the thing it points to could be 
reclaimed in any order.  The sweep phase doesn't attempt to reclaim 
memory in any sort of top-down manner.  I presume it does not work that 
way because trying to do so would slow down the GC.

--bb



More information about the Digitalmars-d mailing list