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

No problem. Another point I just thought of is that it is very common to have functions that allocate resources and only free them if an error happens; otherwise said resources are returned to the caller or otherwise retained, and not freed.

I don't know how well the proposed defer would work here but as long as you can look at actual variables (and not constants), you could do something like this:

    int error = 0;
    void *resource = malloc(N);
    defer [&]{ if (error) free(resource); }

    if ((error = do_stuff(resource)) != 0)
        return NULL; // something went wrong, resource freed

    if ((error = do_more_stuff()) != 0)
        return NULL; // something went wrong, resource freed

    return resource; // all ok, let the caller keep it


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

Search: