Oops, I’m still learning all of this. Thank you for the correction, it is very welcome . I’ll be updating my code soon.
The code I posted (which you can find in my repository) compiles and the test I posted are passing (meaning that
true as soon as the
locker gets out of scope).
I also tested that you cannot call
mem::forget on the
Locker object after having called
lock. Also, I just tested, and you cannot have a
Locker instance that has a lifetime greater than the
T it refers to, because when you call
Locker::lock, it attempts to borrow
T for the entire lifetime of
Locker, and so it fails to compile (which is what we want, I suppose).
Regarding the drop code, note that the
Locker itself does not implement
Drop. Attempting to implement
Drop directly on
Locker was actually my first attempt, but it failed because since
Locker is autoborrowed by
Locker::lock, it couldn’t be borrowed mutable by the
Having one of its fields implement
Drop works, because the fields are dropped right after the end of the
Locker's lifetime, and at this point it is no longer borrowed . I wish this trick of delegating the drop to a field for perma-borrowing struct was documented somewhere, would have saved me a bit of time!
I guess, a thing I need to do to gain confidence that this is safe is to try and put
Locker in a
Rc cycle, and then
lock it. If this proves impossible, then I’ll be happy I guess .
@trentj: Thank you! I wonder if this type would be useful to store callbacks, like was discussed earlier in the thread? I really need to add Trait objects support back soon.
EDIT: I pushed the suggested changes, thank to both of you