Destructor nonsense on dlang.org

deadalnix deadalnix at gmail.com
Sat May 26 10:47:30 PDT 2012


Le 25/05/2012 16:35, Andrei Alexandrescu a écrit :
> On 5/25/12 12:07 AM, Mehrdad wrote:
>> Now, there are two ways a FileStream can get destroyed:
>>
>> 1. Through a manual call to FileStream.Dispose(). In this case, all
>> embedded objects (e.g. SafeFileHandle) are *guaranteed* to be valid, so
>> we simply flush the file and call SafeFileHandle.Dispose() to dispose of
>> the managed resources, and then dispose of all the unmanaged resources
>> (which are primitive fields, guaranteed to be accessible). Furthermore,
>> the object suppresses its own finalizer.
>>
>> 2. Through a garbage-collected call to ~FileStream(). In this case, the
>> managed resources such as SafeFileHandle will be (or is already)
>> destroyed SEPARATELY, and so we do _NOT_ access them. We ONLY dispose of
>> the unmanaged resources, if any, and let the managed resources take care
>> of themselves.
>
> What happens in C# if an object A that has a field referring to object
> B, and the object B has in turn a field referring to object A? That is:
>
> class C { C another; ~this() { writeln(another.another); } }
>
> void main() {
> auto a = new C;
> auto b = new C;
> a.another = b;
> b.another = a;
> }
>
> What happens then? Will the GC nullify references to destroyed objects,
> or will it put them in a zombie state?
>
>
> Thanks,
>
> Andrei

Here is what I suggest :
1/ what is in ~this stay in ~this. You cannot escape a reference to this 
or anything reached throw this of ~this. In other terms, the hidden this 
parameter get scope storage class. This avoid resurrection (something we 
really want, it have caused much trouble in java).
2/ The GC will call all finalizers on objects (here a and b) when they 
are garbage. Finalizers are called in undefined order.
3/ The GC will recycle the memory after all finalizers ran.

In the example above, both writeln will executed and then, both object's 
memory will be recycled.


More information about the Digitalmars-d mailing list