GC: memory collected but destructors not called

Tomer Filiba via Digitalmars-d digitalmars-d at puremagic.com
Mon Nov 10 00:10:08 PST 2014


The following code does not invoke S.~this. If I change `struct 
S` to `class S` - it does. Memory consumption remains constant, 
meaning memory is collected, but destructors are not called.

import std.stdio;
import std.conv;

struct S {
     string s;

     ~this() {
         writeln("~S");
     }
}

void main() {
     auto i = 0;
     S[] arr;

     while (true) {
         arr ~= S("hello " ~ text(i++));
         if (arr.length == 1_000_000) {
             writeln(&arr[8888], " = ", arr[8888].s);
             arr.length = 0;
         }
     }
}


Is it a bug? How can I effectively implement RAII with this 
behavior?

The situation is, I allocate resources for my users and return 
them a handle. I can't control what my users do with this handle, 
they might as well append it to a dynamic array/insert to AA, and 
remove it eventually.
Also, the handle might be shared between several logical 
components, so it's not that one of them can explicitly finalize 
it.

Any workaround for this? Perhaps disallow certain types be 
allocated by the GC (I would actually want this feature very 
much)?


-tomer


More information about the Digitalmars-d mailing list