3 ms·
In all of those examples that talked about which pointer value to capture, it would perhaps have helped to use the built-in (standard, although in my opinion wa
by unwind 5y ago
In all of those examples that talked about which pointer value to capture, it would perhaps have helped to use the built-in (standard, although in my opinion way too few programmers use it) way of indicating that a value won't change, i.e. const:
double * const q = malloc(something);
/* use whatever magic new syntax here, 'q' will not change in this scope */
That wasn't so hard, in my opinion. They could simply let 'defer' fail if the referenced pointer isn't constant. Also, as a micro-wtf I was confused by the use of 'double', for a generic allocation I would have expected void.
- foxfluff 5y agoSo 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