Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The scope guard statement is even better!

https://dlang.org/articles/exception-safe.html

https://dlang.org/spec/statement.html#ScopeGuardStatement

Yes, D also has destructors.



I use this library a lot for scope guards in C++ https://github.com/Neargye/scope_guard, especially for rolling back state on errors, e.g.

In a function that inserts into 4 separate maps, and might fail between each insert, I'll add a scope exit after each insert with the corresponding erase.

Before returning on success, I'll dismiss all the scopes.

I suppose the tradeoff vs RAII in the mutex example is that with the guard you still need to actually call it every time you lock a mutex, so you can still forget it and end up with the unreleased mutex, whereas with RAII that is not possible.


The tradeoff with RAII is once you have 3 things that must all succeed or all fail, that is very clumsy to do with RAII, but easy with scope guard.


Scope guards are neat, particularly since D has had them since 2006! (https://forum.dlang.org/thread/dtr2fg$2vqr$4@digitaldaemon.c...) But they are syntactically confusing since they look like a function invocations with some kind of aliased magic-value passed in.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: