GC-proof resource classes

ZombineDev via Digitalmars-d digitalmars-d at puremagic.com
Sun Aug 30 10:00:22 PDT 2015


On Saturday, 29 August 2015 at 13:14:26 UTC, ponce wrote:
>
> ----------------
>
> ensureNotInGC() is implemented like this:
>
> ----------------
>
> void ensureNotInGC(string resourceName) nothrow
> {
>     debug
>     {
>         import core.exception;
>         try
>         {
>             import core.memory;
>             void* p = GC.malloc(1); // not ideal since it 
> allocates
>             return;
>         }
>         catch(InvalidMemoryOperationError e)
>         {
>             import core.stdc.stdio;
>             fprintf(stderr, "Error: clean-up of %s incorrectly 
> depends on destructors called by the GC.\n", resourceName.ptr);
>             assert(false); // crash
>         }
>     }
> }
>
> --------------
>
>...

BTW, you can use GC.free, instead of GC.malloc, with any non-zero 
invalid memory address, for example: 
http://dpaste.dzfl.pl/af0dc9aaa29d

A more robust solution would be to check if the gcx.running flag 
is raised, or if the GC lock is taken, like this: 
https://gist.github.com/ZombineDev/14076777dff7d879d659, however 
this is not currently possible, because the _gc variable in 
gc.proxy is private and by default gc.proxy is not part of the 
include files.

Since it's really straightforward to expose the information to 
the user, I think this would an easy enhancement.


More information about the Digitalmars-d mailing list