4 ms·
So then you can't for example use defer with a pointer that may get realloc'd in a loop? Or pointer to the root node of tree-to-be-built? What a half-assed de
by foxfluff 5y ago
So then you can't for example use defer with a pointer that may get realloc'd in a loop? Or pointer to the root node of tree-to-be-built? What a half-assed defer, in my opinion.
- unwind 5y agoSure, 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