4 ms·
Starting 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 th
by ufo 6y ago
Starting 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.