4 ms·
What an arrogant use of the word "simple" in the title. * no decision on access to variables * lambdas are involved at all * "appearance in blocks other than
by AndyKelley 5y ago
What an arrogant use of the word "simple" in the title.
* no decision on access to variables
* lambdas are involved at all
* "appearance in blocks other than function bodies [is] implementation-defined"
They cited D in the implementation, but then used Go as the inspiration for the feature. The answer was staring them right there in the face, scope(exit) [1]. Or, you know, they could have cited Zig for the exact syntax they wanted [2].
This feature is completely unusable.
Let me demonstrate. You can't use this inside an if statement:
if (foo) {
const ptr = malloc(...);
defer [&]{ free(ptr); } // implementation defined. get fucked
}
Furthermore, it's go-style, so the defer runs at the end of the function. This is not only implementation defined, it's full-blown undefined behavior because `ptr` goes out of scope before the defer expression runs.
Scope-based defer works great. Go-based defer is already problematic enough in Go; in C it's worse than not having defer in the language at all.
[1]: https://dlang.org/spec/statement.html#scope-guard-statement https://dlang.org/spec/statement.html#scope-guard-statement
[2]: https://ziglang.org/documentation/0.9.0/#defer https://ziglang.org/documentation/0.9.0/#defer
- dnautics 5y agoOh come on now, it's not completely unusable, just "unusable in a ton of important use cases".
- AndyKelley 5y agoPoint taken, but I will defend my claim: The few use cases where it does work are footguns because in the future, you or another collaborator will be tempted to wrap the code into a block, which is normally 100% safe for all other features of the language. It would be easy to do without thinking about it. But if you do it becomes UB as demonstrated above. So the reasonable policy would be to use the same cleanup method everywhere, to avoid footgun firing when code is edited.
- pjmlp 5y agoYep, typical C decision design pattern.
- deleted 5y ago[deleted]