3 ms·
I do prefer the "with"/"try-with-resources" approach because it is explicit. With RAII in C++ there's no visual difference between dumb data objects and object
by tveita 8y ago
I do prefer the "with"/"try-with-resources" approach because it is explicit.
With RAII in C++ there's no visual difference between dumb data objects and objects like locks that are created and held on to mainly to cause implicit side effects.
In Rust this also prevents the compiler from dropping objects early - everything must be held until the end of its scope for the 0.1% of cases where you're RAII managing some externally visible resource. In those cases I would like the programmer to denote "The exact lifetime of this object is important", so the reader knows where to pay attention.
- steveklabnik 8y agoYou can call std::mem::drop if you'd like to drop something early. That's the notation you're asking for. Additionally, part of Rust's core ideas is that the compiler has your back with this kind of thing, so there's less need for comments that say "CAUTION HERE BE DRAGONS." Those things can still be useful for understanding details of your code, of course, but they aren't needed to ensure that things are memory safe. That's what the compiler is for!
- tveita 8y agoI do use explicit drop() calls in my own code to call attention to drops with side effects, but it does not seem to be common practice. My preferred semantics would have been early drops by default, and a must_drop annotation similar to must_use, to say that objects like RwLockReadGuard should be explicitly dropped or moved.
- steveklabnik 8y agoThose semantics would be nice, but they have a lot of unsolved issues: https://gankro.github.io/blah/linear-rust/ https://gankro.github.io/blah/linear-rust/
- ehsanu1 8y agoNice article, but not sure that the changes it talks about are actually required for the suggested semantics. The `must_drop` annotation suggested could just be a lint rather than actually being encoded in the type system. I don't know if early drops is related or possible though.