Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Probably would be easier to pass DisposableStack as an argument to stack all .defer() callbacks in the caller's context?

The problem in that case if if the current function can acquire disposables then error:

    function thing(stack) {
        const f = stack.use(new File(...));
        const g = stack.use(new File(...));
        if (something) {
            throw new Error
        }
        // do more stuff
        return someObject(f, g);
    }
rather than be released on exit, the files will only be released when the parent decides to dispose of its stack.

So what you do instead is use a local stack, and before returning successful control you `move` the disposables from the local stack to the parents', which avoids temporal holes:

    function thing(stack) {
        const local = new DisposableStack;
        const f = local.use(new File(...));
        const g = local.use(new File(...));
        if (something) {
            throw new Error
        }
        // do more stuff

        stack.use(local.move());
        return someObject(f, g);
    }
Although in that case you would probably `move` the stack into `someObject` itself as it takes ownership of the disposables, and have the caller `using` that:

    function thing() {
        const local = new DisposableStack;
        const f = local.use(new File(...));
        const g = local.use(new File(...));
        if (something) {
            throw new Error
        }
        // do more stuff

        return someObject(local.move(), f, g);
    }
In essence, `DisposableStack#move` is a way to emulate RAII's lifetime-based resource management, or the error-only defers some languages have.


(const local should be using local in the snippets).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: