GC-proof resource classes

Sebastiaan Koppe via Digitalmars-d digitalmars-d at puremagic.com
Mon Aug 31 05:54:04 PDT 2015


On Monday, 31 August 2015 at 11:29:21 UTC, ponce wrote:
> On Saturday, 29 August 2015 at 13:14:26 UTC, ponce wrote:
>>
>> Looks ugly? Yes, but it makes the GC acts as a cheap leak 
>> detector, giving accurate messages for still opened resources.
>
> So, let me tell a little success story while using the 
> "GC-proof" resource classes.
> I tested the above idiom on some code I was a bit liberal with 
> and with no thought gone into clean-up.
> I found all resource leaks in ~1 hour, and there was several of 
> them.
>
> The open question that remains is: "can ~this() really be 
> called multiple times?", that would made the idiom less ugly 
> (had to add boolean flags for most resources).

It feels like calling ~this() twice is UB. What about:

```
class MyResource
{
     void* handle;
     this()
     {
         handle = create_handle();
     }
     close()
     {
         if (handle)
             free_handle(handle)
         handle = null;
     }
     ~this()
     {
         enforce(!handle,"Resource leak");
     }
}
```

Nice pattern either way.


More information about the Digitalmars-d mailing list