Destructor semantics

Steven Schveighoffer schveiguy at yahoo.com
Tue Aug 10 15:39:03 PDT 2010


On Tue, 10 Aug 2010 18:09:53 -0400, foobar <foo at bar.com> wrote:

> Steven Schveighoffer Wrote:
>
>> So either you are saying that structs that are in classes are never
>> destroyed, and you have a resource leak, or every class has an
>> auto-generated destructor that calls the struct destructors, and we have
>> the same determinism problem you purport to solve.  If a struct is in a
>> class, it's on the heap.  You have not solved the problem.
>>
>> -Steve
>
> Sorry for the confusion, my explanation wasn't good enough. Let me try  
> again:
>
> We have 4 different cases:
>
> case 1,  class contains a struct:
> a.  the sturct is not an independent block of memory. Instead, it is  
> part of the same memory block of the class instance's memory.
> b. every class has an auto-generated destructor that calls the struct  
> destructors. This is safe because of the point a.

It's only safe if the struct destructor does not deallocate any heap data.

Here is a simple counter case

Class contains struct, which in turn contains another class. The struct  
destructor cannot run because the class it points to may already have been  
cleaned up.

Example:

class A {}

struct B { A a; ~this() {delete a;} }

class C { B b; }

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


More information about the Digitalmars-d mailing list