6 ms·
Sure, that's a valid point. I confess to being not at all used to thinking of/using 'defer' so I don't have a good grasp of the use cases. Thanks.
by unwind 5y ago
Sure, that's a valid point. I confess to being not at all used to thinking of/using 'defer' so I don't have a good grasp of the use cases. Thanks.
- foxfluff 5y agoNo 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