Destructor semantics

Steven Schveighoffer schveiguy at yahoo.com
Wed Aug 11 07:08:27 PDT 2010


On Wed, 11 Aug 2010 09:53:24 -0400, foobar <foo at bar.com> wrote:

> Steven Schveighoffer Wrote:
>
>
>> So if a struct has a class reference, it cannot clean it up?  What if  
>> the
>> class contains a struct that has an open file reference, and you want to
>> clean up that file immediately?  What if that class is private and the
>> struct knows that there are no other references to it?
>>
>> Your "solution" doesn't cover any new ground, we already have the issue
>> that you cannot clean up or even access heap-allocated references in
>> destructors.  The problem is, you don't know from the type system that
>> they are heap-allocated, and the compiler cannot know what is owned and
>> what is not owned, so it can't make the call to restrict you.
>>
>> What we need is a way to determine whether we can access those resources
>> or not in the destructor, and it has nothing to do with struct vs.  
>> class,
>> and everything to do with deterministic vs GC.  Making an artificial
>> distinction on class/struct lines doesn't help.  We have the same  
>> problem,
>> only worse restrictions (now I can't destroy a handle in a class on
>> destruction, I need to put in a struct layer around it).
>>
>> -Steve
>
> I see your point above. I feel that my approach is more structured. I  
> think that at minimum the compiler should prevent (at compile time) any  
> access to reference types from a class dtor.
> I can't imagine what can be your use case for allowing such access. It  
> seems to me that any time you feel the need for one class instance to  
> own a different class instance you should use a struct instead to convey  
> that owned relationship.
>
> Wouldn't you need an annotation system like the one suggested by Bartoz  
> in order to properly implement the owned relationship for reference  
> types?

The point you are still not getting is that reference type != heap.  The  
issue is heap data vs. non-heap data.  Heap data is invalid (except for  
data contained in your current memory block), non-heap data is not.  The  
compiler cannot tell whether a reference type is referencing heap data, so  
it cannot have a say in what to restrict.  That is my whole point.  All it  
can do is tell the destructor if heap references are valid or not (which  
it does not do now), and then it's up to the programmer who knows where  
the data lives (or doesn't know and assumes it could be heap data) to  
determine whether to access it or not.

I agree with what Michael suggested that destructors should be restricted  
to unsafe D.

-Steve


More information about the Digitalmars-d mailing list