ScopeGuard: remove memory leak

Calling ScopeGuard::rollback() would leak the `on_drop` callable; this is
a problem for Box<dyn FnOnce> or closures containing Drop data.
This commit is contained in:
Xiretza 2023-03-13 17:36:56 +01:00 committed by Mahmoud Al-Qudsi
parent aa65856ee0
commit b39715434b

View File

@ -65,7 +65,7 @@ impl<T, F: FnOnce(&mut T)> ScopeGuard<T, F> {
/// Cancels the unwind operation like [`ScopeGuard::cancel()`] but also returns the captured /// Cancels the unwind operation like [`ScopeGuard::cancel()`] but also returns the captured
/// value (consuming the `ScopeGuard` in the process). /// value (consuming the `ScopeGuard` in the process).
pub fn rollback(mut guard: Self) -> T { pub fn rollback(mut guard: Self) -> T {
let _ = guard.on_drop; guard.on_drop.take();
// Safety: we're about to forget the guard altogether // Safety: we're about to forget the guard altogether
let value = unsafe { ManuallyDrop::take(&mut guard.captured) }; let value = unsafe { ManuallyDrop::take(&mut guard.captured) };
std::mem::forget(guard); std::mem::forget(guard);