有一個在沿線的標準庫的一些代碼:如何用cast :: forget()生鏽來避免內存泄漏?
/**
* Swap the values at two mutable locations of the same type, without
* deinitialising or copying either one.
*/
#[inline]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninit();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
ptr::copy_nonoverlapping_memory(x, &*y, 1);
ptr::copy_nonoverlapping_memory(y, &t, 1);
// y and t now point to the same thing, but we need to completely forget `t`
// because it's no longer relevant.
cast::forget(t);
}
}
事實上,這種「創造臨時空間,然後忘記它」的格局變成了好幾次。
根據文檔intrinsics::forget()
取得所有權,但不破壞價值,實際上忘記了目標。
兩個很簡單的問題:
爲什麼這是必要的,而不是讓
t
掉出的範圍和被破壞?爲什麼
forget(t)
不會導致內存泄漏?