The "@safe vs struct destructor" dilemma

Michel Fortin michel.fortin at michelf.ca
Fri Apr 11 20:02:55 PDT 2014


On 2014-04-11 22:22:18 +0000, Nick Sabalausky 
<SeeWebsiteToContactMe at semitwist.com> said:

> On 4/11/2014 3:54 PM, Michel Fortin wrote:
>> 
>> Can destructors be @safe at all? When called from the GC the destructor
>> 1) likely runs in a different thread and 2) can potentially access other
>> destructed objects, those objects might contain pointers to deallocated
>> memory if their destructor manually freed a memory block.
> 
> If destructors can't be @safe, that would seem to create a fairly 
> sizable hole in the utility of @safe.

Well, they are safe as long as they're not called by the GC. I think 
you could make them safe even with the GC by changing things this way:

1- make the GC call the destructor in the same thread the object was 
created in (for non-shared objects), so any access to thread-local 
stuff stays in the right thread, avoiding low-level races.

2- after the destructor is run on an object, wipe out the memory block 
with zeros. This way if another to-be-destructed object has a pointer 
to it, at worse it'll dereference a null pointer. With this you might 
get a sporadic crash when it happens, but that's better than memory 
corruption. You only need to do this when allocated on the GC heap, and 
only pointers need to be zeroed, and only if another object being 
destroyed is still pointing to this object, and perhaps only do it for 
@safe destructors.

-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca



More information about the Digitalmars-d mailing list