Rust:drop(&RefMut) 而不是 drop(RefMut)?

问题描述 投票:0回答:1

我知道当从

RefCell
借一个值时,我可以手动删除它来结束这次借用。

但是,如果我使用对

RefMut
的引用而不是直接使用
RefMut
,则 drop 特性似乎无法结束此借用。

那么,尝试放下

&RefMut
时发生了什么?以及为什么
RefMut
在此操作期间不会被删除。如果引用的
RefMut
不掉线,什么时候掉线?

use std::cell::RefCell;

struct Data {
    pub x: usize,
}

fn main() {
    let c = RefCell::new(Data { x: 42 });
    let b = &c.borrow_mut();
    drop(b);
    let mut d = c.borrow_mut();
    d.x = 43;
    println!("Hello, world!");
}

输出

thread 'main' panicked at 'already borrowed: BorrowMutError', src/main.rs:11:19
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
rust borrow-checker refcell
1个回答
0
投票

只有当它们引用的值也存在于某处时,引用才能存在。在 C/C++ 中,创建对未存储在变量中的临时对象的引用是未定义的行为。然而,在 Rust 中,它是合法的,并且在后台创建一个不可见的变量,它一直存在到当前范围的末尾。这称为临时寿命延长。可以看到更多信息here.

你可以通过引入另一个范围来限制它的生命周期:

use std::cell::RefCell;

struct Data {
    pub x: usize,
}

fn main() {
    let c = RefCell::new(Data { x: 42 });
    {
        let b = &c.borrow_mut();
        drop(b);
    }
    let mut d = c.borrow_mut();
    d.x = 43;
    println!("Hello, world!");
}
Hello, world!

或者通过将其存储在命名变量中:

use std::cell::RefCell;

struct Data {
    pub x: usize,
}

fn main() {
    let c = RefCell::new(Data { x: 42 });

    let b_val = c.borrow_mut();
    let b = &b_val;
    drop(b);
    drop(b_val);

    let mut d = c.borrow_mut();
    d.x = 43;
    println!("Hello, world!");
}
Hello, world!
© www.soinside.com 2019 - 2024. All rights reserved.