31、The Drop trait

The Drop trait

在学析构函数的时候,提到了drop函数:

  • 回收类型占用的内存(即std::mem::size_of bytes)
  • 清理值可能正在管理的任何其他资源(比如String的堆缓冲区)

第二点是Drop trait的用武之地

pub trait Drop {
    fn drop(&mut self);
}

 

Drop trait是一种机制,用于为我们的类型定义其他的清理的逻辑,而不仅仅是编译器自动为我们做的事情。

当值超出它的作用域的时候,将执行我们drop方法里面的内容。

Drop and Copy

学到Copy trait时,提到过如果一个类型管理的资源超出了它在内存中占用的std::mem::size_of以外的其他资源时,则无法实现Copy

 

话说编译器怎么知道一个类型是否管理额外的资源呢?其实就是Drop trait实现的。

如果我们的类型具有明确的Drop实现,编译器会认为我们的类型附加了额外的资源,不允许我们实现Copy

// This is a unit struct, i.e. a struct with no fields.
#[derive(Clone, Copy)]
struct MyType;

impl Drop for MyType {
    fn drop(&mut self) {
       // We don't need to do anything here,
       // it's enough to have an "empty" Drop implementation
    }
}

编译器编译上面的代码就会报错:

error[E0184]: the trait `Copy` cannot be implemented for this type; 
              the type has a destructor
 --> src/lib.rs:2:17
  |
2 | #[derive(Clone, Copy)]
  |                 ^^^^ `Copy` not allowed on types with destructors

即使我们的类型里什么也没有,只要有Drop实现,那么就绝对不能实现Copy了。

练习

感觉现在的练习读不懂题目,莫名其妙的,最后只好看答案,看完答案还是感觉莫名其妙:

// TODO: implement a so-called "Drop bomb": a type that panics when dropped
//  unless a certain operation has been performed on it.
//  You can see the expected API in the tests
//TODO:实现所谓的“Drop bomb”:一种Drop时Panic的类型
//  除非对其进行了某种操作。
//  您可以在测试中看到预期的 API
pub struct DropBomb {
    defused: bool,
}

impl DropBomb {
    pub fn new() -> Self {
        DropBomb { defused: false }
    }

    pub fn defuse(&mut self) {
        self.defused = true;
    }
}

impl Drop for DropBomb {
    fn drop(&mut self) {
        if !self.defused {
            panic!("Boom!");
        }
    }
}

为啥DropBomb要弄个bool类型啊

image-20250915203024332

难道是我英语水平太差了吗?

阅读剩余
THE END