[][src]Function tao_of_rust::ch13::security_abstract::manually_drop

pub fn manually_drop()

使用std::mem:ManuallyDrop手工Drop

ManuallyDrop<T>是一个联合体,Rust不会为联合体自动实现Drop。 因为联合体是所有字段共用内存,不能随便被析构,否则会引起未定义行为。

std::mem::forget<T>函数的实现就是用了ManuallyDrop::new方法

Basic usage: ManuallyDrop示例

use std::mem::ManuallyDrop;
struct Peach;
struct Banana;
struct Melon;
struct FruitBox {
    peach: ManuallyDrop<Peach>,
    melon: Melon,
    banana: ManuallyDrop<Banana>,
}
impl Drop for FruitBox {
   fn drop(&mut self) {
       unsafe {
           ManuallyDrop::drop(&mut self.peach);
           ManuallyDrop::drop(&mut self.banana);
       }
   }
}
fn main(){}Run