Destructor called while object is still alive

Steven Schveighoffer schveiguy at gmail.com
Sat Oct 24 11:56:54 UTC 2020


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.

If you want it cleaned up synchronously, you explicitly destroy the 
object, or provide a function to clean it up.

But if you don't clean it up, and the GC is cleaning up the object, 
there's no reason to leak the resource.

I wrote a program long ago that used classes to manage open files. I 
never worried about cleaning up the file handles, and it worked fine.

-Steve


More information about the Digitalmars-d mailing list