www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - Dtors for heap-allocated structs: Bug or by design?

reply dsimcha <dsimcha yahoo.com> writes:
I've noticed that struct dtors do not get called when a heap-allocated struct
instance is GC'd like they would for a class.  An example is below.  Is this a
bug or is it intentional?

import std.stdio, std.gc;

class foo {

    ~this() {
        writefln(stderr, "foo dtor");
    }
}

struct bar {

    ~this() {
        writefln(stderr, "bar dtor");
    }
}

void main() {  //Prints "foo dtor".  Does not print "bar dtor".
    auto f = new foo;
    f = null;
    auto b = new bar;
    b = null;
    fullCollect;
}
Sep 07 2008
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
"dsimcha" wrote
 I've noticed that struct dtors do not get called when a heap-allocated 
 struct
 instance is GC'd like they would for a class.  An example is below.  Is 
 this a
 bug or is it intentional?

 import std.stdio, std.gc;

 class foo {

    ~this() {
        writefln(stderr, "foo dtor");
    }
 }

 struct bar {

    ~this() {
        writefln(stderr, "bar dtor");
    }
 }

 void main() {  //Prints "foo dtor".  Does not print "bar dtor".
    auto f = new foo;
    f = null;
    auto b = new bar;
    b = null;
    fullCollect;
 }

I'm not an expert on this by any means, but I remember Sean saying something like you may still have registers in the stack that are pointing to the bar. Try doing some other operations before running fullCollect, or swap the order of foo and bar in the main function. -Steve
Sep 08 2008