Why is it a memory ERRO.
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 29 05:32:26 PST 2016
On Friday, 29 January 2016 at 13:22:07 UTC, Mike Parker wrote:
> Your problem is probably that you are calling GC.free in the
> destructor. Don't do this. You don't need to call GC.free at
> all. The GC will collect both your object instance and the
> memory you allocated with new. Never, ever, manipulate GC
> memory in the destructor of a GC-managed object.
Here's a modified version of your program. Every time it prints,
you know the garbage collector has just run a collection cycle.
Every class instance and every 'by' that is allocated will
eventually be free. Not all destructors are guaranteed to run
during the program's lifetime, though. Some will be run after
main exits and the GC shuts down.
import core.thread;
import std.stdio;
class MyClass
{
this(){
by = new ubyte[10000];
id = i;
++i;
}
~this() {
writeln("freed #", id);
}
private:
ubyte[] by;
int id;
static int i;
};
void main()
{
while(true) {
auto obj = new MyClass;
Thread.sleep(5.msecs);
if(MyClass.i == 2000)
break;
}
}
More information about the Digitalmars-d-learn
mailing list