On 05/26/12 13:35, 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?
> 
>> 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.

Everything allocated is collected, though not necessarily destructed. In case
of structs, the GC currently doesn't know about the dtors, so those are never
called.

   import std.stdio;
   struct S { ~this() { writeln("never called"); } }
   void main() { S* sp; while (1) sp = new S(); }

Right now you have to use a class if you need dtors for heap allocated
objects.

artur

Reply via email to