4 ms·
As opposed to... entire program scoped?
by fortytw2 8y ago
As opposed to... entire program scoped?
- mynegation 8y agoAs opposed to any set of matching curly brackets in C++, i.e. just "scope"-d. Do not know the real reason but my wild guess: for simplicity.
- kazinator 8y agoI'm guessing there are some interesting things you can do when the defer list is scoped to the function. Like perhaps this pattern works: loop i over whatever { defer foo(i) } I.e. a loop's iterations can put things into the defer list, which is then executed when the function exits. Whereas if the defer list were block scoped, then each defer would execute immediately on the termination of its enclosing iteration. Also, there is problem with conditional defers like: if (condition) defer whatever Okay, so that is in the surrounding scope. Now I need to add some piece of logic: if (condition) { defer whatever piece of logic } Now it's scoped to the curly braces and executes immediately after "piece of logic" is done? In terms of performance, the defer list has to be an actual run-time object; the compiler can't always optimize away the existence of the defer list. If defer is block-scoped and used in numerous nested scopes of the same function, where the compiler isn't able to remove it, then you get multiple defer list instantiations in the function's stack frame, which is a kind of bloat. These have to be initialized to the empty state on each entry into a block. At most defer list to initialize on entry into a function is less time and space overhead. A more flexible design would be defer to work with named blocks: foo: { bar: { defer h() foo; defer g() bar; defer f(); } } h() is deferred to the termination of foo (thus using foo's defer list); likewise g() in relation to bar, and the f() defer is function scoped.
- cpuguy83 8y agoBut you can just wrap whatever in a closure to scope your defer as needed. This is simple and works well.
- tom_ 8y agoAs opposed to per-scope, like variables in C++.