本文簡要介紹rust語言中 Function std::mem::needs_drop
的用法。
用法
pub const fn needs_drop<T>() -> bool
如果刪除 T
類型的值很重要,則返回 true
。
這純粹是一個優化提示,可以保守地實現:對於實際上不需要刪除的類型,它可能會返回true
。因此,始終返回 true
將是此函數的有效實現。但是,如果此函數實際上返回 false
,那麽您可以確定刪除 T
沒有副作用。
諸如集合之類的低級實現需要手動刪除其數據,應使用此函數以避免在銷毀時不必要地嘗試刪除其所有內容。這在發布版本中可能不會產生什麽影響(其中沒有副作用的循環很容易被檢測和消除),但對於調試版本來說通常是一個巨大的勝利。
請注意, drop_in_place
已經執行了此檢查,因此如果您的工作量可以減少到少量的 drop_in_place
調用,則無需使用它。特別注意,您可以 drop_in_place
切片,這將對所有值進行一次needs_drop 檢查。
因此,像 Vec 這樣的類型隻是 drop_in_place(&mut self[..])
而沒有明確使用 needs_drop
。另一方麵,像 HashMap
這樣的類型必須一次刪除一個值,並且應該使用這個 API。
例子
下麵是一個集合如何使用 needs_drop
的示例:
use std::{mem, ptr};
pub struct MyCollection<T> {
/* ... */
}
impl<T> Drop for MyCollection<T> {
fn drop(&mut self) {
unsafe {
// drop the data
if mem::needs_drop::<T>() {
for x in self.iter_mut() {
ptr::drop_in_place(x);
}
}
self.free_buffer();
}
}
}
相關用法
- Rust never用法及代碼示例
- Rust null_mut用法及代碼示例
- Rust null用法及代碼示例
- Rust UdpSocket.set_multicast_loop_v6用法及代碼示例
- Rust i64.overflowing_add_unsigned用法及代碼示例
- Rust Box.downcast用法及代碼示例
- Rust BTreeMap.last_key_value用法及代碼示例
- Rust str.make_ascii_uppercase用法及代碼示例
- Rust u128.checked_pow用法及代碼示例
- Rust usize.wrapping_mul用法及代碼示例
- Rust AtomicU8.fetch_sub用法及代碼示例
- Rust PanicInfo.payload用法及代碼示例
- Rust MaybeUninit.assume_init_mut用法及代碼示例
- Rust String.try_reserve用法及代碼示例
- Rust Mutex.new用法及代碼示例
- Rust f32.exp用法及代碼示例
- Rust Result.unwrap_or_else用法及代碼示例
- Rust slice.sort_unstable_by_key用法及代碼示例
- Rust Formatter.precision用法及代碼示例
- Rust i128.log2用法及代碼示例
- Rust OsStr.to_ascii_uppercase用法及代碼示例
- Rust f32.hypot用法及代碼示例
- Rust RefCell.try_borrow_unguarded用法及代碼示例
- Rust i16.log10用法及代碼示例
- Rust LowerExp用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Function std::mem::needs_drop。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。