Can I mimick finalizing for immutables / is an immutable file handler unfeasible?

Benny
Sat, 07 Oct 2023 03:04:52 +0000
Internals & Design

I can’t think of other uses for destructors/finalizers in a language without manual deallocations, so I’m using file-closing as an example. It seems to me that I could implement open to open a file and construct an immutable file descriptor, then implement a close to use the file descriptor to close the file. However, my concern is that the file descriptor isn’t handled by the garbage collector, so unlike the typical IOStreams with finalizer(close, x), the file won’t be automatically closed when the descriptor doesn’t outlive a scope. Granted, I could just construct it again to close, but I would need to remember the value. For the sake of the thread, let’s assume an automatic close upon deallocation would help because I am forgetful enough to neglect using higher order functions that automatically handle setup and cleanup, like open’s other method for the open-close pattern.

More thought: Immutable semantics allow several unmonitored copies to represent the same instance, which is notably different from typical languages with manual memory management and destructors. Whatever mimicry of automatic finalization cannot execute for each copy, which sounds impossible in the general case for something that isn’t GC-tracked.

17 posts - 6 participants