by masklinn · 4y ago · 0 comments
The way to do this is pretty much what C++ has in unique_ptr(p, deleter): have the utility RAII class own both the object and the closure, dereference to the wrapped object, and on drop pass the wrapped object to the closure.
Altho
> Eg if I’m creating a temporary file or directory in a function to handle some IO logic, I’ll create a RAII wrapper around a closure that deletes that folder when the scope expires
There are crates for lots of those situations.
https://crates.io/crates/tempfile for instance.
Yeah, but the ergonomics suck. Especially for random cleanup tasks that aren’t necessarily one-object, one-task.
The temp file thing was just an example, actual use case was more domain-specific.
Doesn’t seem much more of a problem? Put a tuple in, get references out, cleanup gets the entire tuple.
If lifetimes get complicated, use refcells and / or Rcs.