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

pub fn forget_drop()

使用std::mem::forget跳过Drop

Basic usage: 转移结构体中字段所有权 - V1

struct A;
struct B;
struct Foo {
    a: A,
    b: B
}
impl Foo {
    fn take(self) -> (A, B) {
        // error[E0509]: cannot move out of type `Foo`, which implements the `Drop` trait
        (self.a, self.b)
   }
}
impl Drop for Foo {
    fn drop(&mut self) {
        // do something
    }
}

fn main(){}Run

Basic usage: 转移结构体中字段所有权 - V2

如果必须要转移结构体所有权,则可以使用std::mem::uninitialized和std::mem::forget

struct A;
struct B;
struct Foo {
    a: A,
    b: B
}
impl Foo {
    // 重新实现take
    fn take(mut self) -> (A, B) {
        // 通过std::mem::uninitialized()进行伪初始化
        // 用于跳过Rust的内存初始化检查
        // 如果此时对a或b进行读写,则有UB风险,谨慎使用
        let a = std::mem::replace(
             &mut self.a, unsafe { std::mem::uninitialized() }
        );
        let b = std::mem::replace(
            &mut self.b, unsafe { std::mem::uninitialized() }
       );
       // 通过forget避免调用结构体实例的drop
       std::mem::forget(self);
       (a, b)
   }
}
impl Drop for Foo {
    fn drop(&mut self) {
        // do something
    }
}

fn main(){}Run