Garbage Collection, Allocators/Deallocators and

Ivo Kasiuk i.kasiuk at gmx.de
Sat Sep 18 10:34:47 PDT 2010


> An interesting case is when using C's malloc for C1 and using the scope
> attribute for c1:
> 
> class C1 {
>   ubyte[1_000_000] buf;
>   new(size_t size) {
>     void* ptr = std.c.stdlib.malloc(size);
>     if (ptr is null)
>       throw new OutOfMemoryError(__FILE__, __LINE__);
>     writefln("C1.new(%d) = %x", size, ptr);
>    return ptr;
>   }
>   delete(void* ptr) {
>     writefln("C1.delete %x", ptr);
>     if (ptr) std.c.stdlib.free(ptr);
>   }
>   this() { writeln("C1()"); }
>   ~this() { writeln("~C1()"); }
> }
> ...
>   scope C1 c1 = new C1;
> 
> In this case, ~C1 gets invoked but not C1.delete. Nevertheless, the
> memory appears to get freed (normal memory consumption, no OutOfMemory).
> How does this happen?

Ok, I figured that out myself: c1 is allocated on the stack in this
case, so no neither the allocator nor the deallocator need to get
called.



More information about the Digitalmars-d-learn mailing list