4 ms·
As someone who has written a lot of C++ but also languages with other constructs that solve similar patterns (defer, finally, etc), I’d say that RAII is definit
by stingraycharles 4y ago
As someone who has written a lot of C++ but also languages with other constructs that solve similar patterns (defer, finally, etc), I’d say that RAII is definitely the most flexible winner of all, but requires more code bloat. You’ll need to write a class with at least a constructor / destructor, give it a name, etc. “Just” a defer statement is absolutely more simple, and puts the resource reallocation logic right next to the allocation logic, which is a nice feature.
- bestouff 4y agoExcept in Rust you nearly never write a destructor. Unless you have very specific needs it's always generated automatically for you.
- zarzavat 4y agoYou can easily implement defer in terms of RAII and lambdas. RAII is a composable building block to build higher level patterns. The whole is greater than the sum of the parts.
- stingraycharles 4y agoThat’s the point I’m trying to make: RAII is more flexible but requires more code than a defer or finally statement.
- IshKebab 4y agoBarely any more. It can be as simple as auto sg = scope_guard([&]() { delete whatever; }); E.g. see this implementation: https://ricab.github.io/scope_guard/ https://ricab.github.io/scope_guard/ But also I should make the point that you generally don't need to write defer-like statements at all when using RAII because it's implemented in the actual type. So it's only more code overall for types that are used only once or maybe twice.
- metadat 4y agoDo you really consider this simple, or is it sarcasm? Simple compared to what?
- IshKebab 4y agoIt is simple. At least if you know C++. I can see why it might look like it has a load of random brackets if you aren't a C++ programmer. But anyway if you're doing C++ right you would rarely need to actually do that whereas you need `defer` in Go all the time.
- pjmlp 4y agoIf that is too much typing, a macro can help.
- pjmlp 4y agoThanks to C++ flexibility there are plenty of "defer" utility classes to chose from.