3 ms·
The "block scope spirit" is there but not quite the same. A lisp "with-" macro requires you to remember to use it. It's not much different manually writing code
by Foober223 6y ago
The "block scope spirit" is there but not quite the same. A lisp "with-" macro requires you to remember to use it. It's not much different manually writing code to release something, in the fact you must remember and explicitly do it.
With C++ RAII you can have a brain fart and forget about freeing a resource, but you're still OK.
- Arnavion 6y agoRAII also follows value scope instead of lexical scope. So if you have a function that creates a value and returns it, the cleanup-via-destructor runs in the scope of the callee, as it should. This doesn't work with lexical-scope-cleanup things like golang's defer (and bugs me when new languages add it instead of destructors). Instead you either have to document that the caller has to remember to defer-cleanup the result, or you have to do funky things like take a callback that receives the value, invoke the callback and defer-cleanup the value.
- int_19h 6y agoIf you have a C++ function that returns by value, the destructor runs twice - first inside the function, to destruct the original, and then inside the caller, to destruct the returned copy. (N)RVO can elide the copy, but it's not guaranteed, and in any case, not always applicable. So destructors are still lexically scoped. What makes C++ flexible in practice is move semantics, which lets you move-return values, such that only the destructor call on the caller side is the one that matters.
- Arnavion 6y agoYou don't need move semantics to have RAII work. If you have a copyable type with a destructor where the cleanup should only happen once, then you already need some kind of refcount to only run the cleanup when the last copy is dropped. Either the refcount is in your own type, or you're wrapping another copyable refcounting type like shared_ptr. Notice how I said "cleanup-via-destructor" rather than just "destructor", for this reason.
- umanwizard 6y agoYou’re right, but one problem with c++ is that types are copiable by default and copies happen automatically and silently in many situations. So something like this is easy to get wrong.