Idomatic way to guarantee to run destructor?

Steven Schveighoffer schveiguy at gmail.com
Sat May 2 20:43:16 UTC 2020


On 5/2/20 3:08 PM, Robert M. Münch wrote:
> On 2020-05-02 18:18:44 +0000, Steven Schveighoffer said:
> 
>> On 5/2/20 4:44 AM, Robert M. Münch wrote:
>>
>>> How would that help, because the class instance is now unusable 
>>> anyway. So I have it around like a zombie and others might think: 
>>> "Hey you look normal, let's get in contact" and then you are doomed...
>>
>> The difference is that if you use it, you get an error and a crash. If 
>> you clean up the memory, that memory could be reallocated to something 
>> else with a completely different type, and now you have memory 
>> corruption.
> 
> I didn't thought about the "memory is re-used" case here...
> 
> And how is the instance made unusable so that a crash happens (which I 
> prefer too!)? Does .destroy zero the memory? Just curious how the crash 
> situation is detected.
> 

destroy sets all the values to the .init value. And it nulls the vtable 
pointer. So any virtual calls will crash with a segfault. non-virtual 
calls won't crash immediately, but generally there are few class calls 
that have all final calls.

And even if they do go through, the .init value should be harmless in 
terms of memory safety.

For reference, destroy calls this function on class instances (Same as 
GC cleanup) where p is really the class reference:

https://github.com/dlang/druntime/blob/999367be8fa5d13a718d951d67c3d580ca13aef1/src/rt/lifetime.d#L1414

You can see in the finally clause, the vptr is set to null.

-Steve


More information about the Digitalmars-d-learn mailing list