沒有更多引用的對象不能立即通過GC.collect()進行垃圾收集,但是可以使用GC.collect()的中間調用。 new,writeln或Thread.sleep將使未引用的對象與GC.collect()可達。GC.collect()object reachability
import std.stdio;
import core.thread;
import core.memory;
class C
{
string m_str;
this(string s) {this.m_str = s;}
~this() { writeln("Destructor: ",this.m_str); }
}
void main()
{
{
C c1 = new C("c1");
}
{
C c2 = new C("c2");
}
//writeln("Adding this writeln means c2 gets destructed at first GC.collect.");
//Thread.sleep(1); // Similarly this call means c2 gets destructed at first GC.collect.
//int x=0; for (int i=0; i<1000_000_000;++i) x+=2*i; // Takes time, but does not make c2 get destructed at first GC.collect.
GC.collect();
writeln("Running second round GC.collect");
GC.collect();
writeln("Exiting...");
}
上面的代碼返回:
析構函數:C1
運行第二輪GC.Collect的
析構函數:C2
退出...
任何人都可以解釋這一點垃圾收集期間對象的可達性?
忘了提及,上面是在Windows 32位,dmd.2.052沒有編譯器標誌。 – John 2011-04-23 00:09:48
請注意,由於D GC是保守的,它並不能保證任何未被引用的對象將被收集。 – 2011-04-23 07:33:54