3 ms·
I definitely wish that Non-Lexical Lifetimes would eagerly drop anything that doesn't implement Drop. It would probably be a breaking change to automatically c
by coder543 4y ago
I definitely wish that Non-Lexical Lifetimes would eagerly drop anything that doesn't implement Drop.
It would probably be a breaking change to automatically call an explicit Drop implementation anywhere other than the end of the current scope, so I think that would have to be left as-is. String doesn't implement Drop, so it could easily be dropped eagerly within the scope as soon as it won't be referenced again. Such a change would be roughly equivalent to any of the compiler optimizations that reorder statements in ways that should be unobservable.
- ______-_-______ 4y ago100%. I would actually go further and say every value should be dropped immediately after its last use, including temporaries in the middle of statements, whether or not it implements Drop. Reuse the same rules that NLL uses. Breaking change yes, so do it next edition. It would lower memory usage in general and solve so many little pain points, not least of which is holding strings across await points.
- varajelle 4y agofn foo(xx : &Mutex<String>) { let lock = xx.lock(); let ptr = &mut *lock as *mut String; unsafe { use_from_c(ptr) } } You get the idea: you don't want the lock or the string to be dropped before the unsafe code, even if the actual string is no longer used. That's the breaking change. It's hard to detect automatically, so hard to justify even in an edition.
- coder543 4y agoI generally agree with you (which is why I made an exception for values with a manual Drop implementation), but to advocate on behalf of the idea… I don’t think it would be too crazy to make a rule that any function that invokes “unsafe” (or is itself defined as an unsafe function) would fall back to the old scope-based drop rules. Worst case scenario is that you’d be dealing with the current level of memory usage efficiency, and you might need to manually call drop if you want something dropped earlier, but in most cases things would be eagerly dropped even sooner. Outside of uses of unsafe, are there any other serious problems with eagerly dropping values that manually implement Drop? Maybe this fallback mechanism would also have to be invoked simply for casting to a raw pointer anywhere in the function. Either way, a list of exceptions to eager drop would arguably be better than not having eager drop, as long as the list was sound. It would still be a breaking change, and would definitely require at least being restricted to a new edition. Some people currently use Drop as a kind of scoped “defer”, especially for things like instrumentation, so maybe it would be time for the language to introduce a proper “defer” statement that exists for that purpose instead of making Drop so lazy for everyone.