Destructors vs. Finalizers

Moritz Maxeiner via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 26 17:20:46 PDT 2017


On Thursday, 27 July 2017 at 00:00:08 UTC, Steven Schveighoffer 
wrote:
> On 7/26/17 7:28 PM, Moritz Maxeiner wrote:
>> On Wednesday, 26 July 2017 at 22:33:23 UTC, Steven 
>> Schveighoffer wrote:
>>> On 7/26/17 2:33 PM, Moritz Maxeiner wrote:

>> A finalizer may freely work on non-pointer members and pointer 
>> members that target objects outside the GC pool which the 
>> programmer knows to be valid at finalization (e.g. they are 
>> manually managed).
>> Whether or not it makes sense for the finalizer to call the 
>> destructor is something the programmer has to decide on a per 
>> use case basis.
>
> No, because a destructor can safely assume it can look at GC 
> members' data. So a finalizer can never call it.

No, whether a finalizer can safely call a destructor depends on 
the destructor's body.
If the destructor doesn't access GC members and doesn't allocate 
using the GC, the finalizer can safely call it. That's why it's 
the programmer's job to determine this on a use case basis.

>
>>>
>>> The destructor is ensured that the entire structure is 
>>> intact, so it can do whatever it wants.
>> 
>> The point is that I saw (and see) no reason for a destructor 
>> to ever call a finalizer.
>
> An example:
>
> class File
> {
>    int fd;
>    ubyte[] buffer;
>
>    // avoiding bikeshed issues by using clear names
>    destructor() { finalizer(); delete buffer; }
>    finalizer() { close(fd); }
> }
>
> No reason to repeat the finalizer code in the destructor.

I concede the point.


More information about the Digitalmars-d mailing list