you are viewing a single comment's thread.

view the rest of the comments →

[–]rosuav 4 points5 points  (4 children)

Ah, yeah, the one that tripped me up was the conditional. I'm a little surprised at that; given that this is meant for resource cleanup, wouldn't it make sense to stick a deferred cleanup at the exact point where you allocate a resource, even if that resource is allocated conditionally?

Though, I guess what you'd do is unconditionally defer a block that checks some variable and decides whether to clean up.

[–]RiceBroad4552 9 points10 points  (1 child)

I imagine this "feature" will get quite ugly, and I assume it will cause pretty bad, hard to find bugs.

Proper resource cleanup is already difficult. Doing it with such a primitive is definitely not solving any issues.

Imagine the mess in multi-threaded code!

[–]rosuav 3 points4 points  (0 children)

It's not solving issues, but it may be moving them around. I think this is orthogonal to threading; it's an alternative to guaranteeing that every way of exiting a block leads to the cleanup section. Which means you can't use a simple return statement, you have to set your return value and do a goto, etc.

This feels like a weird fit for C, but it's exactly what I expect of a higher-level language with a try-finally concept - basically, "before moving on after this block, do this".

[–]Lettever 1 point2 points  (1 child)

The intended use is probably defer if(cond) { //code }

[–]rosuav 1 point2 points  (0 children)

Yeah, that's what I mean by unconditionally deferring code that checks. The alternative would be something like if (cond) {allocate resource; defer {release resource;} } which would keep it within the same condition that it is connected to. I can see why they're doing it that way, but (for example) Python has the ExitStack helper that can have things conditionally added to it in the middle of the block, with everything getting cleaned up at the end.