4 ms·
At first reading, that sounds nigh-impossible to get right in a world where values on the stack can be closed over.
by clhodapp 9y ago
At first reading, that sounds nigh-impossible to get right in a world where values on the stack can be closed over.
- haimez 9y agoAnd voila, rust.
- clhodapp 9y agoExactly! Now let's just amend the value types proposal to include ownership tracking! Should be simple, right?
- _old_dude_ 9y agoThe Value Types proposed in TFA are immutable so no need to have a borrow checker for them :)
- clhodapp 9y agoYou wouldn't need such a sophisticated tracker as Rust has because the implementation here rules out mutable borrows but you'd still need something that looked like ownership tracking or something that looked like garbage collection to correctly implement finalizers on value classes in the face of closure, right? When you close over a stack-allocated immutable value, the low-level effect is that you make a copy of it onto the heap, I'd think. However, at higher-level, you create another reference whose lifespan staves off finalization, no? Edit: I'll add that it's possible that the proper implementation for even a bog-standard, assign-to-a-variable copying would need to work this way (make another finalization-delaying handle) but I think that's less-certainly true.
- dkersten 9y agoClosing over value types could capture by value and make a copy, like you would typically do in C++ when capturing values in lambdas. Of course, since value types are immutable, that would be a bit memory wasteful I guess.
- clhodapp 9y agoYep. But how would you correctly deal with finalizers in the face of those copies? See my comment a bit deeper in the thread.
- dkersten 9y agoYeah, you're right. I guess it doesn't typically make sense to capture a RAII object and have the copy outlive the original, but it also may not make sense to delay the lifecycle of the original since it breaks the expectation of "i put this on the stack, so expect it to finalize when it goes out of scope". Probably best not to mix the two. That is, a stack-allocated RAII object whose finalizer is called when it goes out of scope, which references some data that can be closed over, with a lifetime separate from the RAII object. At the very least, you would call finalizers on both (the stack one when it goes out of scope and the copy when it gets garbage collected) and then its up to the programmer to make sure that shared resources are finalized correctly (eg by keeping a shared reference count...). (I'm thinking a use case where the object represents some external resource that should be freed only once) Sounds pretty error prone though. I suppose that Java's solution is KISS: simply don't support finalizers on value objects.
- barrkel 9y agoThe copy would be living on a heap object only reachable via the interface reference the lambda implements. Deterministic finalization of that copy would be a Hard Problem.