On Friday, 5 March 2021 at 21:02:08 UTC, H. S. Teoh wrote:
If you know when you can deallocate something, that means you don't need the GC to collect it, so you could just allocate it on the malloc heap instead, and call destroy/free once you're done. You could use the C version of malloc/free. You can also optionally use GC.malloc/GC.free.

E.g.:

        class C {...}

        import core.memory : GC;
        C c = cast(C) GC.malloc(C.sizeof);
        ... // use c

        // We're done with c, destroy it
        destroy(c);     // this will call the dtor
        GC.free(cast(void*) c);
c = null; // optional, just to ensure we don't accidentally use it again

Unless the function is nothrow, that should really be:

    import core.memory : GC;
    C c = cast(C) GC.malloc(C.sizeof);
    scope(exit) {
        // We're done with c, destroy it
        destroy(c);     // this will call the dtor
        GC.free(cast(void*) c);
c = null; // optional, just to ensure we don't accidentally use it again
    }
    ... // use c

Or,

    import core.memory : GC;
    C c = cast(C) GC.malloc(C.sizeof);
    try {
        ... // use c
    } finally {
        // We're done with c, destroy it
        destroy(c);     // this will call the dtor
        GC.free(cast(void*) c);
c = null; // optional, just to ensure we don't accidentally use it again
    }

Reply via email to