When is a class's destructor called?
Mike
none at none.com
Sat Dec 28 21:03:41 PST 2013
I'm trying to implement a very minimal D runtime for the ARM
Cortex-M platform. I've been quite successful so far, but I'm
now getting into reference types and I need to understand better
what D does under the hood.
I have a working malloc/free implementation, but don't have a
garbage collector. I'm not yet sure if I want a garbage
collector, so at the moment, I'm trying to implement something
simple.
Consider the following code modeled after the example at
http://dlang.org/memory.html#newdelete:
*************************************
class X
{
__gshared uint _x;
new(size_t nBytes)
{
Trace.WriteLine("Constructing");
void* p;
p = malloc(nBytes);
if (p == null)
{
//TODO:
//throw new OutOfMemoryError();
}
return p;
}
~this()
{
Trace.WriteLine("Destructor");
}
delete(void* p)
{
if (p != null)
{
free(p);
}
Trace.WriteLine("Destroying");
}
}
void DoX()
{
X x = new X();
x._x = 123;
Trace.WriteLine(x._x);
//Why doesn't x's destructor get called here.
}
//My entry point
void main()
{
DoX();
Trace.WriteLine("Done");
while(true) { }
}
**************************************
The output is as follows:
------------------------------
Constructing
56
Done
x's destructor never gets called. What do I need to implement to
have the destructor called when x goes out of scope?
I'm using GDC 4.8 cross-compiled for arm-none-eabi on a Linux
64-bit host.
Thanks,
Mike
More information about the Digitalmars-d-learn
mailing list