Destructor semantics

foobar foo at bar.com
Wed Aug 11 00:12:57 PDT 2010


Rainer Deyke Wrote:

> On 8/10/2010 16:59, foobar wrote:
> > Steven Schveighoffer Wrote:
> >> what happens when GC destroys a C?
> >> 
> >> C::~this(); // auto generated
> >>   B::~this(); // so good so far 
> >>     A::~this(); // oops!  the a is gone, program vomits bits all over itself and
> >> chokes to death.
> >> 
> >> -Steve
> > 
> > This can only happen if you use delete on a class instance. My
> > understanding was that this is going to be removed from D2.
> 
> Same problem without 'delete':
> 
> class A {
>   void dispose();
> }
> 
> struct B {
>   A a;
>   ~this() { a.dispose(); }
> }
> 
> class C {
>   B b;
> }
> 
> C::~this(); // auto generated
>   B::~this(); // so good so far
>     A::dispose(); // oops!
> 
> 
> -- 
> Rainer Deyke - rainerd at eldwood.com

I was posing late at night and hence made a mistake in my suggestion. 
Here's a better example of the problem:
class A{}
struct B{ A a; ~this(); this(ref A); }

auto obj = new A();
auto first = new B(obj);
auto second = new B(obj);

both first and second reference the same instance of A.

The correct semantics for the case of a struct containing a class (more generally, value type contains a reference type):

the struct's dtor does NOT call the class dtor. 

The class dtor would be called either by the GC when it is collected or when it is de-allocated by the user when its memory is managed by a different memory scheme. 

Sorry for this confusion, it'll teach me not to post at 2AM..


More information about the Digitalmars-d mailing list