Destructor nonsense on

Jacob Carlborg doob at
Sat May 26 04:35:25 PDT 2012

On 2012-05-25 14:05, foobar wrote:

>> If you have a pointer to a struct you don't know how it was created.
>> It's possible it's been created with "new", which means the garbage
>> collector needs to delete it.
> let's say we add two classes:
> class FooA {
> A a;
> }
> class FooPA {
> A* pa;
> }
> For the first case, both the class and the struct share the same
> lifetime thus when an instance of FooA is GC-ed, the GC would call A's
> d-tor and allow it to do what-ever (self) cleaning it requires. This
> means the d-tor will always be called.

Is that the cases even if the destructor of FooA isn't called?

> For the second case, The GC will only scan "pa" to find inner class
> instances but will *not* handle the struct value itself.
> In order to clean what "pa" points to, you need to explicitly call the
> destructor yourself.

Are you saying that the GC won't collect a struct allocated with "new"?

"NewExpressions are used to allocate memory on the garbage collected 
heap...". I though that everything allocated via the GC was also 
collected by the GC.

> One way to do this would be to register a callback
> with the GC to get notified when an instance of FooPA is collected and
> inside the callback function maintain a reference-counter.
> This also means that if you allocate a struct value on the heap via
> "new" you are responsible to call delete _yourself_ and the gc will not
> call it for you.
> I think that loosing this small convenience is worth it - we gay more
> orthogonal semantics that are easier to reason about.

/Jacob Carlborg

More information about the Digitalmars-d mailing list