3 ms·
How can you get away from having an explicit guard block? Without one, you couldn't 'defer' to the end of a containing block from within an if/while/do/for/etc
by derriz 6y ago
How can you get away from having an explicit guard block?
Without one, you couldn't 'defer' to the end of a containing block from within an if/while/do/for/etc. block.
When/where the deferred code is executed has to be specified some way so an explicit marker for the defer 'scope' is surely required without severely limiting the utility of the feature.
- anonunivgrad 6y agoYou would just follow the C variable scope rules I think. But I see now how this creates an issue if you want to put the defer, but not the acquisition of the resource it releases, within a control statement.
- ufo 6y agoStarting in page 16, there is a section called "Do we want a guard keyword?" that talks about this. They give an example showing that deferring to the end of the containing block is possible without the guard keyword, although it's a bit wonky, requiring to duplicate the "if". With guard keyword: guard { void *ptr = malloc(12); if (ptr) { defer free(ptr); // Use ptr } // Use ptr some more } // free ptr here Without guard keyword: { void *ptr = malloc(12); defer { if (ptr) free(ptr); } if (ptr) { // Use ptr } // Use ptr some more } // free ptr here
- ludocode 6y agoThis is a silly example of course because you don't have to check free() for null; calling free(NULL) is a no-op. In a more realistic case, say some object was handed off so it shouldn't be cleaned up anymore, you can just add a should_cleanup flag and check it in the defer block. There's really no need for guard. Their other example for guard, running defer in a loop, requires closures. This means it requires dynamic memory allocation and so the complexity goes through the roof.