Destructor called while object is still alive

Johan Engelen j at j.nl
Sat Oct 24 18:37:06 UTC 2020


On Saturday, 24 October 2020 at 11:56:54 UTC, Steven 
Schveighoffer wrote:
> On 10/23/20 7:30 PM, Johan Engelen wrote:
>> On Friday, 23 October 2020 at 20:27:37 UTC, frame wrote:
>>>
>>> Even if I do not run into memory problems, calling the 
>>> destructor on a live object is an unepxected side effect 
>>> which makes the dtor concept useless for me. It closes the 
>>> remote connection the object hold (please don't ask about the 
>>> meaning, it just the way it has to work) and this must not 
>>> happen while the program is still running.
>> 
>> Hi frame,
>>    Regardless of the topic being discussed, you should not do 
>> resource management using ctor/dtor of a GC-managed object. 
>> The dtor is not guaranteed to be called (not even on program 
>> exit). Indeed, the dtor as you know from stack allocated 
>> objects works very differently for GC-allocated objects; this 
>> feels like the dtor concept is useless (I agree, I've also 
>> grown used to RAII-thinking about dtors).
>> 
>
> A destructor is literally for resource management. For example, 
> if a class represents an OS handle, and that handle is 
> encapsulated, the destructor is the right place to clean that 
> up.

My point is that the destructor of a GC-managed object may not be 
called at all, hence in general (!) plain GC+destructor is not 
suitable for resource management. If you are trying to manage 
resources that are released automatically (and correctly) by the 
OS upon program termination, you are lucky and can get away with 
it.

-Johan




More information about the Digitalmars-d mailing list