On Saturday, 26 May 2012 at 11:35:29 UTC, Jacob Carlborg wrote:
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?

Huh? In my model FooA has no destructor.


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"?

http://dlang.org/expression.html#NewExpression

"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.

I indeed propose that structs allocated with "new" will be put in region of the heap *not* managed by the GC. It's a tiny price to pay to get more orthogonal semantics which are easier to reason about. Please note that this only affects code that directly uses pointers which is not common in D and is geared towards more advanced use cases where the programmer will likely want to manage the memory explicitly anyway.


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.


Reply via email to