rust drop

Drop

Drop trait 只有一个方法:drop,当一个对象离开作用域时会自动调用该方法。Drop trait 的主要作用是释放实现者实例拥有的资源。

BoxVecStringFile,以及 Process 是一些实现了 Drop trait 来释放资源的类型的例子。Drop trait 也可以针对任意自定义数据类型手动实现。

下面示例给 drop 函数增加了打印到控制台的功能,用于宣布它在什么时候被调用。(原文:The following example adds a print to console to the drop function to announce when it is called.)

 

 

struct Droppable {
    name: &'static str,
}

// 这个简单的 `drop` 实现添加了打印到控制台的功能。
impl Drop for Droppable {
    fn drop(&mut self) {
        println!("> Dropping {}", self.name);
    }
}

fn main() {
    let _a = Droppable { name: "a" };

    // 代码块 A
    {
        let _b = Droppable { name: "b" };

        // 代码块 B
        {
            let _c = Droppable { name: "c" };
            let _d = Droppable { name: "d" };

            println!("Exiting block B");
        }
        println!("Just exited block B");

        println!("Exiting block A");
    }
    println!("Just exited block A");

    // 变量可以手动使用 `drop` 函数来销毁。
    drop(_a);
    // 试一试 ^ 将此行注释掉。

    println!("end of the main function");

    // `_a` **不会**在这里再次销毁,因为它已经被(手动)销毁。
}
[root@bogon drop]# 

 

 

[root@bogon drop]# cargo build
   Compiling own v0.1.0 (/data2/rust/drop)
    Finished dev [unoptimized + debuginfo] target(s) in 0.37s
[root@bogon drop]# cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/own`
Exiting block B
> Dropping d
> Dropping c
Just exited block B
Exiting block A
> Dropping b
Just exited block A
> Dropping a
end of the main function

 

posted on 2020-12-24 17:10  tycoon3  阅读(182)  评论(0编辑  收藏  举报

导航