3 ms·
I think that gets unwieldy in more complicated cases. You might want to write: if condition_A { acquire_A() defer release_A() } else if
by oconnor663 5y ago
I think that gets unwieldy in more complicated cases. You might want to write:
if condition_A {
acquire_A()
defer release_A()
} else if condition_B() {
acquire_B()
defer release_B()
} else {
acquire_C()
defer release_C()
}
But with block-scoped defer you'd have to write something like:
if condition_A {
acquire_A()
} else if condition_B {
acquire_B()
} else {
acquire_C()
}
defer func() {
if condition_A {
release_A()
} else if condition_B {
release_B()
} else {
release_C()
}
}()
Maybe the syntax here could be better with some kind of defer-if added to the language, but it's the non-locality of the cleanup that's the real downside. The whole point of the defer keyword is to let you put cleanup right next to resource acquisition, to make code easier to audit and maintain, and we lose that here. (Also this version might not even be correct, if the conditions change their values over time.)
To be honest, I think Rust's combination of destructors and move semantics is really the ideal way of doing cleanup, with C++ coming pretty close too. But given a defer keyword, I can see situations where having it block-scoped would be painful.