Interesting. I'm not very proficient in C, this looks like some sort of finalizers for local variables?
Interesting. I'm not very proficient in C, this looks like some sort of finalizers for local variables?
This being C, it's not without its problems. You cannot use it for values that you want to return from the function (as you don't want those to be freed), so any such variables cannot be automatically cleaned up on error paths either. Also there's no automated checking (it's not Rust!)
Note it's {...} scoped, not function scoped, which makes it more useful than Golang's defer.
[1] https://gitlab.com/nbdkit/nbdkit/-/blob/8b36e5a2ea331eed2a73...
if complex_nested_condition {
defer cleanup()
} defer if complex_nested_condition { cleanup() } else { noop() }
In Go, you could do: defer func(run bool) {
if !run { return }
}(condition)
Which admittedly wastes stack space with a noop function in the false case, but whatever.I feel like the number of times I've needed conditional defers is almost zero, while the number of times I've had to make a new function to ensure scoping is correct is huge.
Of especial note, 'mu.Lock(), defer mu.Unlock()' not being scope-based is the largest source of deadlocks in code. People don't use 'defer' because the scoping rules are wrong, code panics before the manual unlock call, and then the program is deadlocked forever.
I would say this is only half true. With some macro magic you can actually also return the values :)
https://github.com/systemd/systemd/blob/0201114bb7f347015ed4...
To be fair though, you probably meant without any such shenanigans.