何时为不再拥有的资源回收存储? [英] When is the storage reclaimed for a resource that is no longer owned?

查看:42
本文介绍了何时为不再拥有的资源回收存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面程序的第 2 行中分配了一个向量资源.当程序结束时,向量资源没有被拥有.如果一个资源根本没有被拥有,它什么时候被回收?是否有使用 Rust 所有权语义和生命周期术语的解释可以让程序员相信该资源确实已被回收?

There is a vector resource that is allocated in line 2 of the program below. When the program ends, the vector resource is not owned. If a resource is not owned at all, when does it get reclaimed? Is there an explanation using the terminology of Rust ownership semantics and lifetimes that could convince a programmer that this resource is indeed reclaimed?

fn main() {
    let mut v = vec![1,2];
    v = vec![3, 4];
}

推荐答案

[无主资源] 什么时候回收?

when does [an unowned resource] get reclaimed?

在 Rust 术语中,一个项目在超出范围时被丢弃,这通常(但不总是)对应于一个块的结尾.当它被丢弃时,属于该项目一部分的所有资源也会被释放.

In Rust terms, an item is dropped when it goes out of scope, which often (but not always) corresponds to the end of a block. When it is dropped, any resources that are part of the item are also released.

Resources 可以表示内存,就像在向量示例中一样,但它也可以对应于其他事物,例如文件句柄或锁.这通常称为资源获取即初始化 (RAII).

Resources can mean memory, as in the vector example, but it can also correspond to other things like a file handle or a lock. This is commonly referred to as Resource Acquisition Is Initialization (RAII).

说服程序员这个资源确实被回收了?

convince a programmer that this resource is indeed reclaimed?

你永远无法说服一个真正不想相信的人^_^.但是,您可以实现 Drop 自己查看物品何时掉落:

You can never convince someone who truly doesn't want to believe ^_^. However, you can implement Drop yourself to see when an item is being dropped:

struct NoisyDrop(u8);

impl Drop for NoisyDrop {
    fn drop(&mut self) {
        println!("Number {} being dropped", self.0);
    }
}

fn main() {
    println!("step 1");
    let mut nd = NoisyDrop(1);
    println!("step 2");
    nd = NoisyDrop(2);
    println!("step 3");
}

这将有输出

step 1
step 2
Number 1 being dropped
step 3
Number 2 being dropped

您可以看到第一个变量在其绑定被替换时被删除,因为不再有任何方法可以获取 NoisyDrop(1) 值.第二个变量因方法结束而超出范围时被删除.

You can see that the first variable is dropped when its binding is replaced as there's no longer any way to get to the NoisyDrop(1) value. The second variable is dropped when it goes out of scope due to the method ending.

所有权语义和生命周期

考虑这个例子:

fn main() {
    let mut v = vec![1];
    v = vec![2];
}

概念上可以写成

fn main() {
    {
        let v = vec![1];
    }
    {
        v = vec![2];
    }
}

还有这个例子

fn main() {
    let v1 = vec![1];
    let v2 = vec![2];
}

可以改写为

fn main() {
    {
        let v1 = vec![1];
        {
            let v2 = vec![2];
        }
    }
}

这些重写显示了每个变量的生命周期.每当您使用泛型生命周期参数调用方法时,块的生命周期将是替换 'a 泛型的具体值.

These rewritings show the lifetime of each variable. Whenever you call a method with a generic lifetime parameter, the lifetime of the block will be the concrete value that gets substituted for the 'a generic.

这篇关于何时为不再拥有的资源回收存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆