I think that defer is actually limited in ways that are good - I don't see it introducing surprising control flow in the same way.
I think that defer is actually limited in ways that are good - I don't see it introducing surprising control flow in the same way.
> RAII has also proven to be quite harmful in cases
The downsides of defer are much worse than the "downsides" of RAII. Defer is manual and error-prone, something that you have to remember to do every single time.
puts("foo");
defer { puts("bar"); }
puts("baz");
defer { puts("qux"); }
puts("corge");
return;
Will evaluate: puts("foo");
puts("baz");
puts("corge");
puts("qux");
puts("bar");
return; puts("foo");
before_defer0:
comefrom after_defer1;
puts("bar");
after_defer0:
comefrom before_defer0;
puts("baz");
before_defer1:
comefrom before_ret;
puts("qux");
after_defer1:
comefrom before_defer1;
puts("corge");
before_ret:
comefrom after_defer0;
return;
---`defer` is obviously not implemented in this way, it will re-order the code to flow top-to-bottom and have fewer branches, but the control flow is effectively the same thing.
In theory a compiler could implement `comefrom` by re-ordering the basic blocks like `defer` does, so that the actual runtime evaluation of code is still top-to-bottom.
It allows library authors to take responsibility for cleaning up resources in exactly one place rather than forcing library users to insert a defer call in every single place the library is used.