strange work of GC

Andrey Derzhavin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 6 12:38:05 PST 2015


class C1
{
	int a1, b1, c1, d1, e1;
	string sdb1;
	this(string s)
	{
		sdb1 = s;
		a1=90;
		b1=19;
		d1=22;
		e1=23;
	}

	~this()
	{
		if (sdb1 == "lll")
		{
			sdb1 = "aaa";
		}

		writeln("disposing "~sdb1);
	}
}

class C2
{
	C1 c1 = null;
	int a2, b2, c2, d2, e2;
	string sdb2;
	this(string s)
	{
		sdb2 = s;
		a2=90;
		b2=19;
		d2=22;
		e2=23;
	}

	~this()
	{

		c1=null;
		writeln("disposing "~sdb2);
	}
};

void fn1()
{
	writeln("start of fn1");
	C2[] arr = new C2[1_000_000];
	
	for (int i=0; i<arr.length; i++)
	{
		arr[i] = new C2(text(i, " C2 class creation"));
		arr[i].c1 = new C1(text(i, " C1 class creation"));

	}
	writeln("end of fn1");
}

void main(string[] args)
{
	fn1();

	bool b = true
	while(b == true)
	{

		Thread.sleep(dur!("msecs")(5));
	}
}


This code never starts the garbage collector, but after execution 
fn1 nothing refers to arr.
As I think, the garbage collector should start destoying of the 
C1 and C2 objects of arr array during the "while" cycle prosess, 
but this does not
happen. Dtors are not called.
If I use the manual destroying of objects C1 and C2 by "destroy" 
method, the dtors of C1 and C2 objects are normally called, but 
it can't be safe.
If I use the GC.collect method after fn1, I get an error: 
"core.exception.InvalidMemoryOperationError@(0)".
Is this a bug of GC or I do something wrong?

Thanks.




More information about the Digitalmars-d-learn mailing list